【问题标题】:How can I test a button which uses props.history for it's onClick with react testing library?如何测试一个使用 props.history 的按钮,因为它是 onClick 和反应测试库?
【发布时间】:2020-06-29 16:16:13
【问题描述】:

这是组件中的按钮,当用户点击它时使用 props.history。

<button data-testid="btn" onClick={ () => props.history.push(`/post/${value}`) } >Search</button>

我尝试像这样测试 onClick :

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

但它会抛出一个错误:

 TypeError: Cannot read property 'push' of undefined
    > 21 |                                      onClick={() => props.history.push(`/post/${value}`)}

我怎样才能完成这项工作并解决这个错误,以便我可以测试使用道具的按钮的 onClick 功能?

【问题讨论】:

    标签: javascript reactjs react-testing-library


    【解决方案1】:

    通过这段代码解决了这个错误:

    const historyMock = { push: jest.fn() };
    render(<Home history={historyMock} />);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-12
      • 2021-05-09
      • 1970-01-01
      • 2022-06-21
      • 2022-11-26
      • 2021-04-14
      • 2020-05-04
      • 2020-01-21
      相关资源
      最近更新 更多