要模拟组件的 change 事件,可以使用 fireEvent 函数,传递一个 change 事件的模拟参数。例如:

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

describe('MyComponent', () => {
  it('renders a text input that updates on change', () => {
    const { getByLabelText } = render(<MyComponent />);  
    const input = getByLabelText('Enter some text');
    fireEvent.change(input, { target: { value: 'hello' } });
    expect(input.value).toBe('hello');
  });
});

在这个例子中,我们使用 render 函数渲染了一个 MyComponent 组件,并通过 getByLabelText 函数获取到了一个 label 为 'Enter some text' 的文本输入框。然后,我们使用 fireEvent.change 函数模拟了一个 change 事件,传递了一个包含 value 属性为 'hello' 的事件对象。最后,我们通过 expect 函数断言输入框的值是否为 'hello'。

React 单元测试:使用 React Testing Library 模拟组件 Change 事件

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

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