首页 > 解决方案 > 到达/路由器导航不使用 react-testing-library 更新历史对象

问题描述

下面的测试继续失败。单击按钮时,它会调用 @reach/router 导航并使用查询字符串/?searchString=abcde,但历史对象在测试中未更新。你如何在没有模拟的情况下使用 react-testing-library 和reach-router 测试编程导航更新

import { createHistory, createMemorySource, LocationProvider, navigate } from "@reach/router"
import { render, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import React from 'react'

test('Can us search path', async () => {
  const history = createHistory(createMemorySource('/'))
  const page = render(
      <LocationProvider history={history}>
        <div>
          <button onClick={() => navigate('/?searchString=abcde')}>navigateButton</button>
        </div>)
      </LocationProvider>
  )
  expect(history.location.search).toEqual('')
  userEvent.click(page.getByText('navigateButton')) //click button to call navigate
  await waitFor(() => expect(history.location.search).toEqual('searchString=abcde')) //FAILS but Should PASS
})

依赖关系

  "@testing-library/react": "^11.2.3",
  "@testing-library/user-event": "^12.6.0",
  "@testing-library/jest-dom": "^5.11.9",
  "react": "^17.0.1",
  "react-dom": "^17.0.1",
  "@reach/router": "^1.3.4",

标签: reactjsreact-testing-libraryreach-router

解决方案


推荐阅读