【问题标题】:How to test that a function prop was called in react-testing-library如何测试在 react-testing-library 中调用了函数 prop
【发布时间】:2021-10-19 04:31:17
【问题描述】:

有3个文件:

文件 1: helpers.js

export const helpers = () => ({
  bar: () => 'Bar was called',
});

文件 2: TestComponent.js

import React from 'react';
import { helpers } from './helpers';

const TestComponent = () => {
  const { bar } = helpers();
  return (
    <><button onClick={bar}/></>
  );
};

export default TestComponent;

文件 3: TestComponent.test.js

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

jest.mock('./helpers', () => ({
  helpers: jest.fn(),
}));

test('bar is called', () => {
  helpers.mockImplementation(() => ({
    bar: jest.fn(),
  }));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(???????).toHaveBeenCalled();
});

这一行是关键:

expect(???????).toHaveBeenCalled();

问题:如何测试bar 函数是否被调用?我期待类似于expect(helpers().bar) 的东西会起作用。但事实并非如此。

【问题讨论】:

  • 你是对的。谢谢!你可以继续写答案,我会接受的。
  • 好的,谢谢我现在添加了答案

标签: javascript jestjs react-testing-library


【解决方案1】:

将函数保存在变量中并在expect中使用

test('bar is called', () => {
  const bar = jest.fn()
  helpers.mockImplementation(() => ({bar}));

  render(
    <TestComponent />,
  );

  userEvent.click(screen.getByRole('button'));

  expect(bar).toHaveBeenCalled();
});

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2021-04-26
    • 2020-10-17
    • 2019-08-29
    • 2021-11-30
    • 2020-05-10
    • 2019-05-21
    • 2021-02-28
    • 2019-11-11
    相关资源
    最近更新 更多