Enzyme + Jest Practice
1. How to use enzyme with jest
1.1 children()
This blog mainly describe some practice on how to write tests in jest with enzyme.
// This test make sure the component only have one h1 element
describe('<Add /> rendering', () => {
it('should render one <h1>', () => {
let wrapper = shallow(<Add />);
expect(wrapper.children('h1')).toHaveLength(1);
});
});
1.2 snapshot
// For snapshot test, jest will help you create a directory named __snapshots__ with the autogenerated file inside with the extension `.snap`. Push snapshot into the repository and store it along with the test
// it means same as test
it('render correctly text component', () => {
const TextInputComponent = renderer.create(<TextInput />).toJSON();
expect(TextInputComponent).toMatchSnapshot();
});
1.3 Test with props in your component
it('check month and years dropdowns displayed', () => {
const props = {
showMonthYearsDropdowns: true
},
DateInputComponent = mount(<DateInput {...props} />).find('.datepicker');
expect(DateInputComponent.hasClass('react-datepicker-hide-month')).toEqual(true);
});
it('render date input correctly with null value', () => {
const props = {
value: null
},
DateInputComponent = mount(<DateInput {...props} />);
expect((DateInputComponent).prop('value')).toEqual(null);
});
it('check the type of value', () => {
const props = {
value: '10.03.2018'
},
DateInputComponent = mount(<DateInput {...props} />);
expect(DateInputComponent.prop('value')).toBeString();
});
1.4 Test events
it('check the onChange callback', () => {
const onChange = jest.fn(),
props = {
value: '20.01.2018',
onChange
},
DateInputComponent = mount(<DateInput {...props} />).find('input');
DateInputComponent.simulate('change', { target: {value: moment('2018-01-22')} });
expect(onChange).toHaveBeenCalledWith('22.01.2018');
});
it('check DatePicker popup open', () => {
const DateComponent = mount(<DateInput />),
dateInput = DateComponent.find("input[type='text']");
dateInput.simulate('click');
expect(DateComponent.find('.react-datepicker')).toHaveLength(1);
});
2. Some tips
One component should have only one snapshot.
- mainly because if one fails, most likely the others will fail too
Test props.
- check the render od default prop values
- check the custom value of the prop, set your own value and do tests
Testing data types
- you could use
jest-extended
to test the type of data
- you could use
Event testing
- mock event -> simulate it -> expect event was called
- mock event -> simulate event with params -> expect event was called with passed params
- pass necessary props -> render component -> simulate event -> expect a certain behavior on called event
Reference
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 stone2paul@gmail.com
文章标题:Enzyme + Jest Practice
文章字数:440
本文作者:Leilei Chen
发布时间:2020-05-23, 08:29:18
最后更新:2021-07-01, 12:43:48
原始链接:https://www.llchen60.com/Enzyme-Jest-Practice/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。