【问题标题】:Testing subsequent function call on an Async function from React function component测试来自 React 函数组件的 Async 函数的后续函数调用
【发布时间】:2021-05-05 01:54:36
【问题描述】:

我正在尝试测试是否调用了 navigate 函数。我开玩笑地嘲笑了这个组件,但是由于 async / promise 函数,它没有及时调用该函数进行测试

组件

import React, { useEffect, useState } from 'react';
...
import { Dialog } from '../../../../common/components/Dialog';

const Component = () => {

  ...

  const handleSave= async (value) => {
    const { id } = await newRecord(value);
    navigate(APP_ROUTES.SOMELOCATION(id));
  };

  return (
    <button onClick={() => handleSave(someValue)} />
  );
};

测试

import { navigate } form '@reach/router';
jest.mock('@reach/router');


it('should call navigate when button is clicked', () => {
  wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});

但是,如果您这样做,它确实有效: setTimeout(() =&gt; { expect(navigate).toHaveBeenCalled() }, 100)

【问题讨论】:

  • navigate 定义在哪里?
  • 在第 1 行:导入 { navigate } form '@reach/router';

标签: javascript reactjs jestjs


【解决方案1】:

我认为这是因为鼠标点击是异步的,所以你应该等到它结束,试试这个:

it('should call navigate when button is clicked', async () => {
  await wrapper.find('button').simulate('click');
  expect(navigate).toHaveBeenCalled();
});

【讨论】:

  • 您好@I_Shayderov 不幸的是那没有用。虽然我认为这是解决方案的一部分。
【解决方案2】:

遇到后:Stackoverflow: Flush all promises

我将此添加到我的测试中,现在它似乎正在通过。所以现在我的测试看起来像这样:

const flushPromises = () => new Promise(setImmediate);


it('should call navigate when button is clicked', async () => {
  wrapper.find('button').simulate('click');
  await flushPromises();
  expect(navigate).toHaveBeenCalled();
});

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 2018-07-25
    • 2021-11-17
    • 2018-07-05
    • 1970-01-01
    • 2020-02-05
    • 2019-01-13
    • 2021-08-08
    • 2022-06-10
    相关资源
    最近更新 更多