reactjs - 测试 React 功能组件承诺使用 Jest 的行为,
问题描述
我有一个 React 函数组件。我将一个函数作为道具传递给组件,它返回一个承诺。我在一个事件上使用该函数onClick
,一旦 promise 得到解决,我就会更改组件的状态。就像是:
import React, { useState } from 'react';
function myComponent({ aPromiseReturningFunction }) {
const [myState, setState] = useState('12');
const clickHandler = () => {
aPromiseReturningFunction().then(() => { setState('123') })
};
return <div onClick={ clickHandler }>{myState}</div>
}
在我的测试中:
const myFunc = jest.fn(() => Promise.resolve(true));
const componentWrapper = shallow(<myComponent aPromiseReturningFunction={ myFunc }/>);
componentWrapper.simulate('click');
expect(componentWrapper.text()).toEqual('123');
显然以上失败了,但我还没有找到任何可以解释如何正确测试上述内容的东西。当然,如果我改变了承诺之外的状态,测试就通过了。
有什么建议么?
解决方案
由于click
在承诺之后更新状态,也就是异步,我会使用act
import { act } from 'react-dom/test-utils'; // other testing libraries have similar methods that test async events
const myFunc = jest.fn(() => Promise.resolve(true));
it('updates text after onclick', () => {
const componentWrapper = shallow(<myComponent aPromiseReturningFunction={ myFunc }/>);
act(() => {
componentWrapper.simulate('click');
});
expect(componentWrapper.text()).toEqual('123');
});
推荐阅读
- ios - Xcode 10.2 GNU 风格的内联汇编被禁用
- excel - 有没有办法计算 Y 和 Z 匹配设置条件的 X 列中的唯一值?
- wordpress - 在 1 处设置字段值并将这些值应用于所有其他页面
- sql-server - 如何在模型上运行 RANK() 函数
- c# - 允许查看但不选择 ComboBox 项目
- python - 使用 python 及其库从给定的短文本中提取关键字/短语
- javascript - 如何在不实例化 Ace 编辑器实例的情况下使用 Ace 编辑器验证器?
- r - 如何计算某些列名向量的最大值并将值分配给新列?
- docker - 为什么创建docker服务后docker容器名称末尾有一个随机数
- symfony - 对于翻译,我可以同时使用 xlf 和 yml 文件吗?