我有这个测试(React、Vitest 和测试库):
import { describe, expect, it } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
describe('App button Problem', () => {
it('types in the input correctly', async () => {
render(<input type={'text'} disabled={false}/> );
const input : HTMLInputElement = screen.getByRole('textbox');
fireEvent.input(input, { target: { value: 'test' } });
expect( input.value).toBe('test'); // this is ok
});
it('does not types in the input if disabled', async () => {
render(<input type={'text'} disabled={true}/> );
const input : HTMLInputElement = screen.getByRole('textbox');
fireEvent.input(input, { target: { value: 'test' } });
expect( input.value).toBe(''); // this fails (why?)
});
});
我收到此错误:
AssertionError: expected 'test' to be '' // Object.is equality
Expected :
Actual :test
知道为什么吗?
fireEvent.input()
不尊重 disabled
元素的 input
属性。
但是您可以将
fireEvent
替换为 userEvent
中的 @testing-library/user-event
,这会尊重 disabled
属性:
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
describe('App button Problem', () => {
it('types in the input correctly', async () => {
render(<input type={'text'} disabled={false} />);
const input: HTMLInputElement = screen.getByRole('textbox');
await userEvent.type(input, 'test');
expect(input.value).toBe('test'); // this is ok
});
it('does not type in the input if disabled', async () => {
render(<input type={'text'} disabled={true} />);
const input: HTMLInputElement = screen.getByRole('textbox');
// Try to type in the input (userEvent respects disabled attribute)
await userEvent.type(input, 'test');
// The input value should remain unchanged
expect(input.value).toBe('');
});
});