React Jest Mock在渲染组件时在组件内部使用的变量

puruo6ea  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(151)

我有一个测试用例,我需要渲染一个组件,然后检查渲染的组件。这个渲染的值取决于组件内部使用的变量。

Triangle.tsx:

export const Triangle = ({
     prop1,
      prop2
    }: Props): JSX.Element => {
      const [variable1] = useVarState();
      if(!variable1) {
        return <></>;
      return (<div></div>);

字符串

TriangleTest.tsx:

describe('Testing component', () => {
          test('Main Elements', () => {
            const prop1 = jest.fn();
            const prop2 = undefined;
        
            const container = render(
              <Triangle
                prop1={prop1}
                prop2={prop2}
              />
            );
        
            const triangle = container.container.querySelector(
              '.Triangle'
            );
            expect(triangle).not.toBeNull();
        }
    }


如何模拟变量的值?useVarState返回基于useContext的Map。

yrdbyhpb

yrdbyhpb1#

在继续之前,请确保Triangle组件为其div元素分配了一个类名,以便可以在测试用例中识别和选择它:

// TriangleTest.tsx

import React from 'react';
import { render } from '@testing-library/react';
import { Triangle } from './Triangle';
import * as hookModule from './path-to-your-hook'; // Adjust this import to the correct path

// Mock the entire module
jest.mock('./path-to-your-hook', () => ({
  ...jest.requireActual('./path-to-your-hook'), // Import actual module implementations
  useVarState: jest.fn(), // Mock only useVarState
}));

describe('Testing component', () => {
  test('Main Elements', () => {
    const prop1 = jest.fn();
    const prop2 = undefined;

    // Cast the mocked function to jest.Mock and set the return value
    (hookModule.useVarState as jest.Mock).mockReturnValue([true]);

    const { container } = render(
      <Triangle
        prop1={prop1}
        prop2={prop2}
      />
    );

    const triangle = container.querySelector(
      '.Triangle'
    );

    expect(triangle).not.toBeNull();
  });
});

字符串
这应该解决你的问题。

**编辑:**更新代码。

相关问题