【问题标题】:How can I test an input with Jest如何使用 Jest 测试输入
【发布时间】:2022-11-21 19:53:29
【问题描述】:

我一直在试图弄清楚如何测试不同的输入法,但由于我是这种测试方法的新手,所以我什至无法接近答案。这是我所拥有的:

const App = (props) => {
    const newGame = props.newGame;
    const [typeracertext, setTyperacertext] = useState(props.typeracertext);
    const [wholeText, setWholeText] = useState("");

    const onChange = (e) => {

       //here I have code that read the input and is comparing it with variable - typeracertext and if so, it sets the property wholeText to that value
};
    return (
        <input ref={(node) => this.textInput = node}  placeholder="Message..." onChange={onChange}></input> 
    );
}

所以我想弄清楚的是一个测试,应该将 typeracertext 设置为某个值(例如“这是一个测试”),并将输入值设置为“This”,所以如果它通过了 onChange() 检查它应该将 wholeText 设置为“This”。我希望这是有道理的。

这是我能得到的最好的,我不知道我应该在“期望”上写什么。

test('Test the input value', () => {
const node = this.textInput;
node.value = 'This';
ReactTestUtils.Simulate.change(node);
expect()
});

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    由于这是一个 React 应用程序,我建议您利用 React 测试库来简化此操作

    import React from 'react';
    import { fireEvent, render, screen } from '@testing-library/react';
    import userEvent from '@testing-library/user-event';
    
    // In describe block
    test('Test input component', () => {
      const onChange = jest.fn();
      render(<InputComponent onChange={onChange} data-test-id="input" />);
      const input = screen.getByTestId('input');
      fireEvent.change(input, { target: { value: 'a value' } });
      // You can also do this with userEvent
      userEvent.type(input, 'test')
      // Check if change event was fired
      expect((input as HTMLInputElement).onchange).toHaveBeenCalled();
    });
    

    请参阅文档here

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 1970-01-01
      • 2018-08-06
      • 2020-01-27
      • 2019-06-09
      • 1970-01-01
      • 2017-11-11
      • 2020-06-12
      • 1970-01-01
      相关资源
      最近更新 更多