title: Ice.js单元测试 author: Gamehu tags: - ice.js categories: - 前端 date: 2020-08-06 15:22:00 --- ### 背景 新建构是基于Ice.js搭建的,在写单元测试的时候遇到一些问题,此篇作为填坑记录。 一开始ice是不支持运行单元测试,因为暴露出来的ice是alias出来的虚包,所以直接在单元测试里import是没法运行的,遂到社区提了issue,前几天传来利好,有了alpha版本能支持写单元测试了,所以下面实践一把。 ### 实操 #### **services** 测试services(ice框架)里的方法 比如: ``` import { request } from "ice"; const mockId = "00000000-0d00-0000-0000-000000000000"; export default { async fetchList(params, config={}) { return await request.post( "/api/v1/domain/getResourcesByDomainId", { ...params, id: mockId, }, { ...config } ); }, }; ``` 测试用例: ``` /** * @jest-environment node */ //@jest-environment node 表示测试环境你,默认为jsdom(类浏览器),node表示为node服务的方式(测试跨域请求时需要用到) import listService from '../../../../src/pages/ResourceCenter/services/list' import getCookie from '../../../_helper/getCookie' let headers = {} beforeEach(async () => { const Cookie = await getCookie() headers = { Cookie } }) describe('fetchList', () => { test('listService fetchList', async () => { const params = { pageNum: 1, pageSize: 10 } const config = { withCredentials: true, headers: { ...headers }, } const data = await listService.fetchList(params, config) expect(data).not.toBeNull() }) }) ``` #### 带store的组件 比如: ``` import React, { useEffect } from 'react'; import { Grid, Tab } from '@alifd/next'; import { store as pageStore } from 'ice/ResourceCenter'; import ResourceList from './components/list.jsx'; import styles from './index.module.scss'; import ResourceTypeTree from './components/tree.jsx'; import DetailConfig from './components/detail_config.jsx'; const { Row, Col } = Grid; const AlarmAnalyze = () => { const [treeState, treeDispatchers] = pageStore.useModel('tree'); const [listState, listDispatchers] = pageStore.useModel('list'); useEffect(() => { treeDispatchers.fetchTree(); listDispatchers.fetchList(); }, []); return (