无法使用 Jest 单元测试模拟输入中的用户类型。 fireEvent、userEvent 不起作用

问题描述 投票:0回答:2
reactjs unit-testing jestjs react-testing-library user-event
2个回答
7
投票

来自文档键盘(文本,选项)

如果您只想模拟按下键盘上的按钮,则应该使用

userEvent.keyboard
。如果您只是想方便地将一些文本插入输入字段或文本区域,则应该使用
userEvent.type

尝试:

import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'

test("the input field should take user's input", async () => {
  render(<testModal />);
  await userEvent.type(screen.getByTestId("add-input"), 'testTyping');
  expect(inputMessage).toHaveValue("testTyping");
})

0
投票

我想测试输入验证错误是否在

onChange
之后触发,但是
fireEvent.change
没有为我完成这项工作。

感谢@lin-du的回答,我能够使用

userEvent
触发错误。 但仍然不明白
fireEvent.change
是如何做到的,因为我正在组件中使用 onChange 处理错误。

  it('shows error if input is greater than 50', async () => {
  const user = userEvent.setup();
  const { getByTestId, getByText } = render(<TestComponent />);
  const inputElem = getByTestId('input-test-id');
  await user.type(inputElem, '51');
  const errorText = getByText('value must be less than 50.');
  expect(errorText).toBeTruthy();
});
© www.soinside.com 2019 - 2024. All rights reserved.