【问题标题】:Can't mock function multiple times react, testing无法模拟函数多次反应,测试
【发布时间】:2021-08-22 23:38:24
【问题描述】:

我想测试我的组件:

const Courses: React.FC = () => {
  const { data, error } = useSWR(
    'some url...',
    fetcher
  );

  console.log(data, error);

  if (error) {
    return (
      <CoursesContainer>
        <Error>Something went wrong.</Error>
      </CoursesContainer>
    );
  }

  if (!data) return <Loader title="loader" />;

  return (
    <CoursesContainer>
      <CollapsibleTable courses={data} />
    </CoursesContainer>
  );
};

export default Courses;

但我不知道为什么我不能模拟它为每个测试返回不同的值。我试过了:

jest.mock('../../utils/fetcher', () => ({
  fetcher: jest
    .fn()
    .mockReturnValue('default')
    .mockReturnValueOnce('first call')
    .mockReturnValueOnce('second call'),
  readData: jest.fn(),
}));

test('Basic render. fetch pending', async () => {
  const component = render(<Courses />);
  await waitFor(() => component.findByTitle('loader'));
  expect(component.baseElement).toMatchSnapshot();
});

test('Basic render, fetch success', async () => {
  const component = render(<Courses />);
  await waitFor(() => component.findByText('CollapsibleTable'));
  expect(component.baseElement).toMatchSnapshot();
});

test('Basic render, fetch error', async () => {
  const component = render(<Courses />);
  await waitFor(() => component.findByText('Something went wrong.'));
  expect(component.baseElement).toMatchSnapshot();
});

而且效果不好。对于每个测试,只有 first callconsole.log() - 来自 Courses.tsx 的 console.log(data, error);。 来自jest的反馈:

  console.log
    undefined undefined

      at Courses (src/components/Courses.tsx:14:11)

  console.log
    first call undefined

      at Courses (src/components/Courses.tsx:14:11)

  console.log
    first call undefined

      at Courses (src/components/Courses.tsx:14:11)

  console.log
    first call undefined

      at Courses (src/components/Courses.tsx:14:11)

当然,第三次测试 (Basic render, fetch error) 也因此失败。

我不能改用spyOn(),因为我的fetcher 是没有对象的单独函数。

@@ 更新@@

有我的fetcher 和readData 函数:

const fetcher = (url: string) => {
  return fetch(url)
    .then((response) => response.json())
    .then((data: Array<IFetchData>) => readData(data));
};

const readData = (data: Array<IFetchData>) => {
  let myData: Array<ICourse> = [];

  [ there are some simple operations which create new myData array with 
    properties which I need (there is not any async operations)]

  return myData;
};

【问题讨论】:

  • fetcher 和 readData 是否返回承诺?
  • 我刚刚在底部添加了这些函数来提问
  • 你无法达到你想要的。请参阅更新的答案。 @poldeeek

标签: javascript reactjs jestjs mocking fetch


【解决方案1】:

您还必须为 readData 提供模拟实现。

根据 jest 规范,

我们可以使用 jest.fn() 创建一个模拟函数。如果没有给出实现,则模拟函数在调用时将返回 undefined。


这将使您的测试更有意义。

 await waitForElementToBeRemoved(() => component.getByTitle('loader'));

我们正在等待加载器标题被删除,以确保标题首先显示出来,现在它在加载器完成时被删除。

jest.mock('../../utils/fetcher', () => ({
  fetcher: jest
    .fn()
    .mockResolvedValue('default')
    .mockResolvedValueOnce('first call')
    .mockResolvedValueOnce('second call'),
  readData: jest.fn().mockResolvedValue('Read call'), //provide reseolve value
//jest.fn() returns undefined when we dont't provide implementation
}));

test('Basic render. fetch pending', async () => {
  const component = render(<Courses />);
  await waitForElementToBeRemoved(() => component.getByTitle('loader'));
  expect(component.baseElement).toMatchSnapshot();
});

test('Basic render, fetch success', async () => {
  const component = render(<Courses />);
  await waitForElementToBeRemoved(() => component.getByText('CollapsibleTable'));
  expect(component.baseElement).toMatchSnapshot();
});

test('Basic render, fetch error', async () => {
  const component = render(<Courses />);
  await waitForElementToBeRemoved(() => component.getByText('Something went wrong.'));
  expect(component.baseElement).toMatchSnapshot();
});

@更新的答案

很抱歉,你无法实现你想要的。原因是渲染函数在您的测试用例中只调用一次,这意味着fetcher 和readData API 只会调用一次。

const mockFn = jest.fn();
jest.mock('../../utils/fetcher', () => ({
  fetcher: mockFn.mockResolvedValueOnce('first call'),
  readData: mockFn.mockResolvedValue(['Read call']), // returns array
}));
test('Basic render. fetch pending', async () => {
  const component = render(<Courses />);
  await waitForElementToBeRemoved(() => component.getByTitle('loader'));
  expect(mockFn).toHaveBeenCalledTimes(1); // test passed
  expect(component.baseElement).toMatchSnapshot();
});

即使您再次提供 mockResolvedValue,它也会给 undefined,因为渲染函数没有机会第二次调用模拟版本的 fetcher 和 readData。

【讨论】:

  • 感谢waitForElementToBeRemoved 函数建议 :) 模拟仍然存在同样的问题。模拟 readData() 没有解决问题。我刚刚在我的问题底部添加了readData 和fetcher。
  • 是的...我自己解决了这个问题:v 我尝试了几个mockImplementationOnce,但是对于在每个测试中呈现的组件,只有第一个@987654336 @调用:/
  • 顺便说一句,这是模拟 API 的最佳示例?。现在,大多数人已经开始使用MSW 来模拟 api。
  • 我写这个应用程序只是为了学习和娱乐目的,所以我会检查Mock Service Worker的解决方案:) 无论如何感谢您的时间
【解决方案2】:

看起来您的 MockReturnValue 链出现故障。默认应该是最后一个,像这样:

jest.mock('../../utils/fetcher', () => ({
  fetcher: jest
    .fn()
    .mockReturnValueOnce('first call')
    .mockReturnValueOnce('second call')
    .mockReturnValue('default'),
  readData: jest.fn(),
}));

从这里查看批准的答案: Jest mock the same function twice with different arguments

【讨论】:

  • 嗯...你能发布 fetcher 模块的代码吗?可能更容易诊断。
  • 我刚刚将这些函数(fetcher 和readData)添加到底部的问题中
猜你喜欢
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2022-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多