react单测样例
// 采用了facebook的jest+enzyme
// 1. 展示型组件测试,意思就是要确保每一次的修改都是符合预期的
describe('XJLayerCard', () => {
it('renders correctly', () => {
const wrapper = Enzyme.render(<XJLayerCard {...mockData}/>);
expect(toJson(wrapper)).toMatchSnapshot();
});
});
// 2.功能性组件测试,就是要覆盖到一个组件的基础功能,能够确保每一个修改之后,跑完单元测试,能够确定之前的功能正常
import React from 'react'; import Enzyme from 'enzyme'; import AppInput from '../AppInput'; import toJson from 'enzyme-to-json' import initialStore from '@/../__mocks__/store.js'; import appInfoData from '@/../__mocks__/appInfo.js' import { Provider } from 'react-redux'; import configureStore from '@/entries/maker/redux/store'; import { updateAppInfo } from '@/entries/maker/redux/action'; import moxios from 'moxios'; import instance from '@/api/instance' import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({ adapter: new Adapter() }); let store; let wrapper; beforeEach(() => { moxios.install(instance); store = configureStore(initialStore); wrapper = Enzyme.mount( <Provider store={store}> <AppInput onChange={(obj) => { store.dispatch(updateAppInfo(obj)) }}/> </Provider> ); }); afterEach(function () { moxios.uninstall(instance); }); describe('demo', () => { it('renders correctly', () => { expect(toJson(wrapper)).toMatchSnapshot(); }); it('click div, select show', () => { // 渲染选项框正常 expect(wrapper.find('.xj-appinput-item').length).toEqual(2); // 一开始没有输入框 expect(wrapper.find('input').length).toEqual(0); wrapper.find('.xj-appinput-value-wrapper').at(0).simulate('click'); expect(wrapper.find('input').length).toEqual(1); }); it('updateAppInfo action', (done) => { // 拦截请求 moxios.stubRequest('/app/get', { status: 200, responseText: 'success' }); // 点击下拉框中的第一个,会触发action wrapper.find('.xj-appinput-item').at(0).simulate('click'); moxios.wait(() => { // mock数据 let request = moxios.requests.mostRecent(); request.respondWith({ status: 200, response: appInfoData }).then((res) => { // input输入框消失 expect(wrapper.find('input').length).toEqual(0); // 选中的app展示出来 expect(wrapper.find('.xj-appinput-wrapper').length).toEqual(1); expect(toJson(wrapper)).toMatchSnapshot(); done(); }).catch(err => { console.log(err); }); }); }); });
https://github.com/axios/moxios