要模拟组件的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/fsLv 著作权归作者所有。请勿转载和采集!

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