使用 React Testing Library,可以通过 render 函数渲染组件并获取到组件实例。因此,可以在 render 函数中传入一个包含初始 state 的 props,来模拟组件的初始状态。

例如,假设我们有一个名为 Counter 的组件,初始状态为 count 为 0。我们可以这样写测试用例:

import React from 'react';
import { render, screen } from '@testing-library/react';
import Counter from './Counter';

test('renders initial count', () => {
  render(<Counter count={0} />); 
  const countElement = screen.getByText(/Count: 0/i);
  expect(countElement).toBeInTheDocument();
});

在这个例子中,我们在 render 函数中传入了一个包含初始 state 的 props:count 为 0。这样,我们就可以测试组件在初始状态下是否正确渲染了 count 为 0 的文本。

需要注意的是,在测试用例中,我们只需要测试组件的输出是否符合预期,而不需要直接操作组件的 state。因此,通过传入初始 state 来测试组件的初始状态是一种比较简单、直接的方式。

React 单元测试:使用 React Testing Library 模拟初始 state

原文地址: https://www.cveoy.top/t/topic/oha6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录