首页 > 解决方案 > 如何测试使用 props.history 的按钮 onClick 在 rtl 中的功能?

问题描述

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

<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 start 时,应用程序本身运行良好,但仅在测试时失败。我该如何解决这个 undefined 的推送?

标签: javascriptreactjsreact-testing-library

解决方案


您必须将道具传递给渲染的组件,在这种情况下 - <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);
    });

推荐阅读