繁体   English   中英

如何在 rtl 中测试使用 props.history 的按钮 onClick 的 function?

[英]How can I test a button onClick which uses props.history for it's function in 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 function :

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM