Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jestjs Jest+React测试库-等待模拟异步函数完成_Jestjs_React Testing Library - Fatal编程技术网

Jestjs Jest+React测试库-等待模拟异步函数完成

Jestjs Jest+React测试库-等待模拟异步函数完成,jestjs,react-testing-library,Jestjs,React Testing Library,我的componentDidMount触发对异步函数的调用,但根据该函数的结果,它可能不会导致任何DOM更改。有什么方法可以让我在测试中等待函数完成吗 下面是一个示例-单击按钮最初是禁用的。如果异步函数返回true,则应启用单击按钮: myAsyncFunction.mockImplementation(() => true); const {queryByText} = render(<Component />); const button = que

我的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=>expectmockAPI.toHaveBeenCalledTimes1
你可能想开火:等待,等待;渲染后组件:const{queryByText}=render;等待等待;是的,wait现在已经被弃用了,我相信waitFor=>{};是新的等价物。然而,我在某个地方读到,我认为在react测试库文档的前一个版本中,空等待被认为是不好的做法,你应该等待一些具体的东西,而不是等待!谢谢,自从我提出这个问题以来,这个文本已经更新了:-。据我所知,这将等待函数被调用,而不是等待承诺被解决。不过,既然现在文档中已经明确了,我想没关系