异步调用 React 后的测试函数调用

时间:2021-04-24 10:12:44

标签: reactjs typescript testing jestjs

我在测试组件 props 中传递的函数时遇到了很多麻烦。该函数将在 API 调用完成后被调用,在示例中将被替换为 setTimeout 调用。

我有一个只有点击按钮的组件:

export interface SubComponentProps {
  onClickFunc: () => void;
}

function SubComponent({onClickFunc}: SubComponentProps) {
  return <button onClick={onClickFunc} data-testid="button-click-me-id">Click Me!</button>
}

export default SubComponent;

围绕该组件的包装器将调用异步函数,然后在他的道具中传递一个函数。

import SubComponent from './SubComponent';

export interface AppProps {
  onClicked?: () => void;
}

function App({onClicked}: AppProps) {
  function callOnClicked() {
    setTimeout(() => {
      if(onClicked) {
        onClicked();
      }
    }, 2000);
  }

  return (
    <SubComponent onClickFunc={callOnClicked} />
  );
}

export default App;

当我运行应用程序时,一切都很顺利,但我无法测试 onClicked 函数是否被调用。我正在尝试这样的测试:

import { render, screen } from '@testing-library/react';
import App from './App';
import userEvent from '@testing-library/user-event';

test('should call prop function', () => {
  const onClick = jest.fn();

  render(<App onClicked={onClick} />);
  userEvent.click(screen.getByTestId('button-click-me-id'));

  expect(onClick).toHaveBeenCalled();
});

还尝试了一个间谍功能,就像这样:

import { render, screen } from '@testing-library/react';
import App from './App';
import userEvent from '@testing-library/user-event';

test('should call prop function', () => {
  const props = {
    onClicked: () => console.log('called')
  };
  const spy = jest.spyOn(props, 'onClicked');

  render(<App {...props} />);
  userEvent.click(screen.getByTestId('button-click-me-id'));

  expect(spy).toHaveBeenCalled();
});

似乎没有任何效果,我已经厌倦了几乎所有的事情,所以任何帮助都可能有用。提前致谢!

0 个答案:

没有答案