NavLink 上的 fireEvent.click() 不会触发反应测试库中的 History.push()

问题描述 投票:0回答:1

我试图验证在单击异步 api 调用后生成的链接后是否调用了某个路由。我事先测试了链接的出现和正确的 href 属性,现在想要模拟用户单击反应 NavLink (模拟应该由单击调用的方法)。

fireEvent 似乎既没有调用history.push() 也没有调用handleClick()。我总是收到此错误:

Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

我尝试添加鼠标按钮和冒泡(根据测试:在带有react-testing-library的react-router-dom中的链接上单击(fireEvent.click)不会触发和其他帖子),但没有成功。这是代码:

import {findByTestId, fireEvent, render, screen, waitFor} from '@testing-library/react';
import { MemoryRouter } from "react-router-dom";
import { createMemoryHistory } from 'history';
import Card from "./Card";

test('click on card leads to newgame/gameName route', async () => {
    const history = createMemoryHistory();
    history.push = jest.fn();
    render(<MemoryRouter history={history}><Card element={{name: "3ts", title: "3Ts", description: "Tic Tac Toe"}}/></MemoryRouter>);
    const card = await screen.findByTestId('card-link');
    expect(card).toHaveAttribute('href', '/newGame/3ts');
    card.handleClick = jest.fn(); // I tried this after history.push didn't seem to work
    fireEvent(card, new MouseEvent('click', {bubbles: true})); // I tried adding bubbling after I read another user's situation where this helped.

    expect(card.handleClick).toHaveBeenCalled();
    expect(history.push).toHaveBeenCalled();
})
reactjs asynchronous react-router mouseevent react-testing-library
1个回答
0
投票

如果您想在 MemoryWrapper 中测试单个组件,您必须配置一些 Routes,如 docu 中所示。这取决于您的测试目标,但如果您的 Card 组件中有一个 NavLink 路由到“aGame”网址,您的测试可能如下所示:

test('click card and jump to agame', async () => {
//arrange
render(<MemoryRouter>
    <Routes>
        <Route path="/" element={<Card
            element={
                {
                    name: "aName",
                    title: "a Title",
                    description: "A description",
                }
            }
        />}/>
        <Route path="/aGame/:something" element={<NewGame/>}/>
    </Routes>
</MemoryRouter>);

let navLink = await screen.findByTestId('card-link');

//act
fireEvent.click(navLink);

//assert
let aGameDiv = screen.getByTestId('agame');
expect(aGameDiv).toBeInTheDocument();
});

如果您想测试您的路由设置,您应该在 App.js 或路由设置发生的任何地方进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.