My componentDidMount()
触发对异步函数的调用,但根据该函数的结果,它可能不会导致任何 DOM 更改。有什么方法可以等待该函数在测试中完成吗?
这是一个示例 - 单击按钮最初被禁用。如果异步函数返回 true,则应启用单击按钮:
myAsyncFunction.mockImplementation(() => true);
const {queryByText} = render(<Component />);
const button = queryByText("Click");
expect(button).toBeDisabled();
await waitFor( () => expect(button).not.toBeDisabled() );
expect(button).not.toBeDisabled();
但如果它返回 false,按钮将保持禁用状态:
myAsyncFunction.mockImplementation(() => false); // async returning different value
const {queryByText} = render(<Component />);
const button = queryByText("Click");
expect(button).toBeDisabled();
await waitFor( () => {} ); // <== **** CODE SMELL ****
expect(button).toBeDisabled();
第二个测试确实有效,但是空的waitFor()
被认为是不好的做法。有什么办法可以避免这种情况吗?
在文档中waitFor https://testing-library.com/docs/dom-testing-library/api-async#waitfor,建议等待您的异步函数.toHaveBeenCalled
like so
await waitFor(() => expect(mockAPI).toHaveBeenCalledTimes(1))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)