即使在 React 测试库中禁用,输入仍然会获取值

问题描述 投票:0回答:1

我有这个测试(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

知道为什么吗?

reactjs react-testing-library vitest
1个回答
0
投票
在测试环境中,默认情况下,

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(''); 
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.