无法使用 Jest 模拟在 React 组件之外定义的构造函数

问题描述 投票:0回答:1

我在使用 jest mock 进行测试时遇到问题。

问题很简单,如果我在组件外部定义构造函数,为什么我无法正确模拟它?

(*)在此示例中,我使用的是reactQuery,但此场景与此无关。

import * as reactQuery from '@tanstack/react-query';
import { render } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

//If I place here the definition of the client it doesn't work
const client = new QueryClient();

const TestComponent = () => {
  //<--- Instead if I place it here (inside the component) it works. Why???

  return (
    <QueryClientProvider client={client}>
      <div>Some Component</div>
    </QueryClientProvider>
  );
};

jest.mock(`@tanstack/react-query`);

it(`Test`, () => {
  const constructorSpy = jest.spyOn(reactQuery, `QueryClient`);

  render(<TestComponent />);

  expect(constructorSpy).toHaveBeenCalled();

  /*
    Error: expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0
   */

});

感谢您的帮助。

javascript reactjs typescript jestjs mocking
1个回答
0
投票

我不知道你为什么同时使用

jest.mock()
jest.spyOn()
。以下解决方案仅使用
jest.mock()
:

test-component.test.tsx

import React from 'react';
import { render } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const client = new QueryClient();

export const TestComponent = () => {
  return (
    <QueryClientProvider client={client}>
      <div>Some Component</div>
    </QueryClientProvider>
  );
};

jest.mock(`@tanstack/react-query`);

it(`Test`, () => {
  render(<TestComponent />);
  expect(QueryClient).toHaveBeenCalled();
});

测试结果:

 PASS  stackoverflow/78678507/test-component.test.tsx
  √ Test (9 ms)
                                                                                                                                                                                                                                                    
Test Suites: 1 passed, 1 total                                                                                                                                                                                                                      
Tests:       1 passed, 1 total                                                                                                                                                                                                                      
Snapshots:   0 total
Time:        1.032 s
Ran all test suites related to changed files.
© www.soinside.com 2019 - 2024. All rights reserved.