在 Jest (RTL) 中模拟 React 组件时遇到困难

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

基本上,我正在为一个名为

LocalLink
的本地组件编写测试,并且我想确保它将正确的 prop
 slug
传递给第三个包组件
 ThirdPackageLink
,所以我尝试模拟 ThirdPackageLink ,如下所示。然而,下面的代码并没有按预期工作,看起来 jest.mock 根本不起作用,它根本不模拟
ThirdPackageLink
。只有将
jest.mock('@/path-to-component')
放在描述块之外,我才能使其工作。

import LocalLink from './link';
import { within, render as renderInternal } from '@testing-library/react';

// If i put ``jest.mock('@/path-to-component')`` at here, it would work.

describe('LocalLink', () => {

  it('Should render correct slug', async () => {
  // For some reason, jest mock does not work here.
  jest.mock('@/path-to-component', () => ({
    ThirdPackageLink: ({ slug }: props) => `This component has slug: ${slug}`
  }));

    const { container } = render(<LocalLink path={path} />);
    expect(
      within(container).getByText(
        `This component has slug: ${path}`
      )
    ).toBeInTheDocument();
  });
});

感谢您的帮助!

我尝试了以下方法,但不起作用。

  1. it
    块内使用jest.doMock
 jest.mock('@/path-to-component', () => ({
    ThirdPackageLink: ({ slug }: props) => `This component has slug: ${slug}`
  }));
reactjs jestjs react-testing-library
1个回答
0
投票

考虑到您的进一步背景,我可能会这样做。

全局(在您的测试套件中)将

ThirdPackageLink
包装在
jest.fn()
中,这样您就可以获得能够模拟它的好处,同时也可以使用它的真实实现。

这就是我的意思:

jest.mock('@/path-to-component',() => {
  const { ThirdPackageLink } = jest.requireActual('@/path-to-component');
  return {
    ThirdPackageLink:jest.fn(ThirdPackageLink)
  }
});

import { ThirdPackageLink } from '@/path-to-component';

const mockedThirdPackageLink = jest.mocked(ThirdPackageLink); // if you're using typescript

describe('LocalLink',() => {
   it('should work with the real module',() => {
        // your test
   });

   it('should work with the mocked module',() => {
      mockedThirdPackageLink.mockImplementationOnce(({ slug }: props) => `This component has slug: ${slug}`)

    
      const { container } = render(<LocalLink path={path} />);
      expect(
        within(container).getByText(
          `This component has slug: ${path}`
        )
      ).toBeInTheDocument();      

   });

});

这是我的偏好,但绝对不是唯一的方法。

另一个确实是遵循

jest.doMock
文档

describe('LocalLink',() => {
   it('should work with the real module',() => {
        // your test
   });

   it('should work with the mocked module',() => {
       jest.doMock('@/path-to-component',() => ({ThirdPackageLink:jest.fn(({ slug }: props) => `This component has slug: ${slug}`)}))
    
       const { container } = render(<LocalLink path={path} />);
       expect(
         within(container).getByText(
           `This component has slug: ${path}`
         )
       ).toBeInTheDocument();      

   });

});
© www.soinside.com 2019 - 2024. All rights reserved.