如何在rtl中测试使用props.history作为其功能的按钮onClick?

时间:2020-06-29 07:04:21

标签: javascript reactjs react-testing-library

我正在使用反应测试库,我想测试一个按钮:

<button data-testid="btn" onClick={() => props.history.push(`/post/${value}`)} > Search </button>
<input data-testid="input" type="text" value={value} onChange={(e) => handle(e.target.value)} />

我测试了它的onClick函数,如下所示:

test('Button should navigate the url when enabled', () => {
        render(<Home />);
        const input = screen.getByTestId('input');
        const btn = screen.getByTestId('btn');
        fireEvent.change(input, { target: { value: '12' } });
        fireEvent.click(btn);
    });

但这给我一个错误:

    TypeError: Cannot read property 'push' of undefined

      19 |                              <button
      20 |                                      data-testid="btn"
    > 21 |                                      onClick={() => props.history.push(`/post/${value}`)}
         |                                                                   ^
      22 |                                      disabled={!value}
      23 |                                      type="submit"
      24 |                              >

当我启动npm时,该应用程序本身运行良好,但仅在测试时失败。 如何解决未定义的问题?

1 个答案:

答案 0 :(得分:1)

在这种情况下,您必须将道具传递到渲染的组件-<Home />

import history from 'history' // Or a file you made that contains an instance of history

test('Button should navigate the url when enabled', () => {
        render(<Home history={history} {...otherProps} />);
        const input = screen.getByTestId('input');
        const btn = screen.getByTestId('btn');
        fireEvent.change(input, { target: { value: '12' } });
        fireEvent.click(btn);
    });