javascript - “setProps()”没有在 Jest 中触发“useEffect”
问题描述
当我在测试用例中更新功能组件的道具时,它不会触发 useEffect。但是它正在更新 myComp 中的道具。
组件示例:
const myComp = ({userId, myAction}) => {
useEffect(() => {
myAction(userId);
}, [userId]);
return <div>Test</div>
}
测试用例示例:
.....
describe('Testing MyComp', () => {
it('should call myAction with userID', () => {
const userId = 'testId';
wrapper.setProps({userId});
expect(myAction).toHaveBeenCalledWith(userId);
});
});
解决方案
useEffect()
并且useLayoutEffect()
不要在 React 浅渲染器中被调用。请参阅组件浅渲染时未调用 useEffect
和此问题。
您应该使用该mount
功能。
例如
index.tsx
:
import React, { useEffect } from 'react';
export const MyComp = ({ userId, myAction }) => {
useEffect(() => {
myAction(userId);
}, [userId]);
return <div>Test</div>;
};
index.test.tsx
:
import React from 'react';
import { mount } from 'enzyme';
import { MyComp } from './';
describe('67312763', () => {
it('should pass', () => {
const props = {
userId: '1',
myAction: jest.fn(),
};
const wrapper = mount(<MyComp {...props} />);
expect(props.myAction).toHaveBeenCalledWith('1');
const userId = '2';
wrapper.setProps({ userId });
expect(props.myAction).toHaveBeenCalledWith('2');
});
});
测试结果:
PASS examples/67312763/index.test.tsx (7.221 s)
67312763
✓ should pass (31 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.731 s
包版本:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest": "^26.6.3",
"jest-enzyme": "^7.1.2",
"react": "^16.14.0",
推荐阅读
- android - Android如何将触摸事件坐标发送到另一个不同尺寸和密度的屏幕并保留它?
- shell - Shellscript 打开 csvfile 并打印第 4 列,如果该字段为 null,则打印 null
- asp.net - 如何将数据存储在内存中并由其他按钮单击事件使用来显示数据?
- amazon-web-services - AWS 目的地不工作,我不知道为什么
- jython - 带有 jython 脚本的 wsadmin 给出错误 AttributeError: 'javapackage' object has no attribute 'SEC_SEGMENT'
- python - Python 3 - 'While loop' 验证用户输入是否在 2 个数字之间
- jquery - 使用键盘进行选择时的事件
- python - 如何为 jupyter notebook 手动安装 chromium?
- angular - PrimeNG 主题字体覆盖 Angular 应用程序字体
- javascript - 如何将 API 响应变量从服务传递到多个控制器