首页 > 解决方案 > React Jest/React-testing-Library 路由更改无法正常工作

问题描述

我一直在尝试记录单击锚标记时的 URL 更改。虽然这在实际页面上有效,但在我用 Jest 编写测试时却不行。

这是代码:

import { renderApp } from "<src>/tests/util";
import { fireEvent, wait } from "react-testing-library";

import {
  getLocationAPath,
  getLocationBPath,
  getLocationCPath
} from "<src>/paths";

let getByDataQa;
let history;

beforeEach(() => {
  ({ getByDataQa, history } = renderApp(getLocationAPath(), {}));
});

test("Validate if routes work", async () => {
  let routePath;
  fireEvent.click(getByDataQa("Container.locB"));
  //await wait();
  routePath = getLocationBPath();
  expect(history.location.pathname).toEqual(routePath);

  fireEvent.click(getByDataQa("Container.locC"));
  routePath = getLocationCPath();
  console.log(history.location.pathname);
  expect(history.location.pathname).toEqual(routePath);

});

标签: reactjsjestjsreact-testing-library

解决方案


我替换anchorshrefto Links。这解决了这个问题。


推荐阅读