Open naseeihity opened 6 years ago
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import MyComponent from './MyComponent';
import Foo from './Foo';
describe('<MyComponent />', () => {
it('renders three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.length(3);
});
it('renders an `.icon-star`', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.icon-star')).to.have.length(1);
});
it('renders children when passed in', () => {
const wrapper = shallow((
<MyComponent>
<div className="unique" />
</MyComponent>
));
expect(wrapper.contains(<div className="unique" />)).to.equal(true);
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(<Foo onButtonClick={onButtonClick} />);
wrapper.find('button').simulate('click');
expect(onButtonClick).to.have.property('callCount', 1);
});
});
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Foo from '../Foo';
describe('A suite', function() {
it('should render without throwing an error', function() {
expect(shallow(<Foo />).contains(<div className="foo">Bar</div>)).toBe(true);
});
it('should be selectable by class "foo"', function() {
expect(shallow(<Foo />).is('.foo')).toBe(true);
});
it('should mount in a full DOM', function() {
expect(mount(<Foo />).find('.foo').length).toBe(1);
});
it('should render to static HTML', function() {
expect(render(<Foo />).text()).toEqual('Bar');
});
});
Snapshot 测试
一般用于UI测试,配合React Component可以直观地比较UI的变化。
第一次运行会生成一次snapshot,之后再运行,如果UI发生了变化,测试用例就会失败。这时,需要去检查是bug还是UI确实更新了,如果是bug则需要修复,如果是UI更新,可以通过命令
jest --updateSnapshot
来更新。该命令会更新所有的用例UI变化,所以应该在执行该命令前修复相应的bug,或者通过参数--testNamePattern
来更新具体的用例。最佳实践
视snapshots为代码 利用相关工具进行代码美化:
eslint-plugin-jest
with itsno-large-snapshots
option测试应该是确定的(多次测试应该得到相同的结果)
使用描述性快照名称
推荐将最新的snapshot更新到版本管理工具中
Async Mock实例
Timer Mock实例
使用
jest.useFakeTimers()
mocksetTimeout, setInterval, clearTimeout, clearInterval
.runAllTimers
runOnlyPendingTimers 处理timer嵌套的问题
advanceTimersByTime(msToRun) 设置向前运行多少毫秒