【问题标题】:fireevent problem in react-testing-libraryreact-testing-library中的fireevent问题
【发布时间】:2019-08-31 21:07:29
【问题描述】:

我正在为我的 react 应用程序使用 react-testing-library。 在一个测试用例中,我需要在文本框中填充一些值并聚焦。

这是测试脚本-

it('searchbox wrapper',async()=>{
    let wrapper=getSearchBoxWrapperInstance('')
    let inputBox=wrapper.findByTestId('inputText');
    inputBox.value='12345';
    fireEvent(inputBox,'focusOut');

})

运行测试用例时出现以下错误 -

TypeError: element.dispatchEvent is not a function

  79 |     let inputBox=wrapper.findByTestId('inputText');
  80 |     inputBox.value='12345';
> 81 |     fireEvent(inputBox,'focusOut');
     |     ^
  82 |     //fireEvent('Blur',
  83 | 
  84 |     //await (() => wrapper.getByText('')))

  at fireEvent (node_modules/dom-testing-library/dist/events.js:533:18)

如果我可以提供更多信息,请告诉我

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    我假设getSearchBoxWrapperInstance 返回render 的结果。

    试试这是否可行:

    it('searchbox wrapper',async()=>{
      let wrapper=getSearchBoxWrapperInstance('')
      let inputBox=wrapper.findByTestId('inputText');
      fireEvent.change(inputBox, { target:  { value: '12345' } });
      fireEvent.focusOut(inputBox);
      // In alternative you could try fireEvent.blur
    })
    

    findByTestId 也有可能找不到您的元素。尝试将其注销以查看是否是这种情况或使用getByTestId,如果找不到该元素,则会出错。

    【讨论】:

    • 我现在收到此错误 - “给定元素没有值设置器”,在这一行 - fireEvent.change(inputBox, { target: { value: '1234567' } });
    • 您确定inputBox 是您所期望的吗?
    • 有没有办法使用这个库打印日志...我找不到足够的文档
    • const { debug } = render() 默认情况下,如果您调用 debug(),您将打印整个 DOM。你也可以debug(inputBox)
    【解决方案2】:
    // import ing userevent
    import userEvent from '@testing-library/user-event';
    // detecting the input in component by the placeholder name
    const input = screen.queryByPlaceholderText('input placeholder 
    name');
    // entering data in the userEvent
    userEvent.type(input,'typing some value into the input');
    // invoking blur functiuonality.
    fireEvent.blur(input);
    

    【讨论】:

    • 欢迎来到 SO?你能解释一下你的问题是什么吗?
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2019-08-18
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2020-10-17
    相关资源
    最近更新 更多