【发布时间】:2021-09-02 14:31:46
【问题描述】:
我有一个 React 函数组件。
我将一个函数作为道具传递给组件,它返回一个承诺。
我在onClick 事件上使用该函数,一旦承诺得到解决,我就会更改组件的状态。
比如:
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');
显然以上失败了,但我还没有找到任何可以解释如何正确测试上述内容的东西。当然,如果我在 Promise 之外更改状态,则测试通过。
有什么建议吗?
【问题讨论】: