我是靠谱客的博主 贤惠小松鼠,这篇文章主要介绍React Hooks 组件 Jest写法,现在分享给大家,希望可以做个参考。

React 拥有了更加强大的 Hooks书写方式,本人公司基本都抛弃使用class组件写法,随之jest单元测试写法也有些变化。

下面上一个demo

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// demo.js import React from 'react'; const TestComponent = () => { const [count, setCount] = React.useState(0); return ( <h3>{count}</h3> <span> <button id="count-up" type="button" onClick={() => setCount(count + 1)}>Count Up</button> <button id="count-down" type="button" onClick={() => setCount(count - 1)}>Count Down</button> <button id="zero-count" type="button" onClick={() => setCount(0)}>Zero</button> </span> ); } export default TestComponent; // demo.test.js import React from 'react'; import Enzyme from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import TestComponent from './FunctionalComponent'; Enzyme.configure({ adapter: new Adapter() }); describe('<TestComponent />', () => { let wrapper; const setState = jest.fn(); const useStateSpy = jest.spyOn(React, 'useState') useStateSpy.mockImplementation((init) => [init, setState]); beforeEach(() => { wrapper = Enzyme.shallow(<TestComponent />); }); afterEach(() => { jest.clearAllMocks(); }); describe('Count Up', () => { it('calls setCount with count + 1', () => { wrapper.find('#count-up').props().onClick(); expect(setState).toHaveBeenCalledWith(1); }); }); describe('Count Down', () => { it('calls setCount with count - 1', () => { wrapper.find('#count-down').props().onClick(); expect(setState).toHaveBeenCalledWith(-1); }); }); describe('Zero', () => { it('calls setCount with 0', () => { wrapper.find('#zero-count').props().onClick(); expect(setState).toHaveBeenCalledWith(0); }); }); });

最后

以上就是贤惠小松鼠最近收集整理的关于React Hooks 组件 Jest写法的全部内容,更多相关React内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部