1

使用到达路由器的应用程序。有两个页面,apage 和 bpage 渲染 APage 和 BPage
Apage 有一个标题和按钮。单击按钮时,应用程序导航到 bpage。

应用程序.js

import { Router, navigate } from "@reach/router";

export default function AppWithRouter() {


  const APage = () => {

    const handle = () => {
       navigate('bpage')
    }

    return(
      <div>
        <h1>A Page</h1>
      <button onClick={handle}>Sign In</button>
      </div>
    )   

  }

  const BPage = () => (<div><h1>B Page</h1>BPage</div>)


  return (
      <Router>
        <APage path="/apage" />
        <BPage path="/bpage" />
      </Router>
  );
}

使用 @testing-library/react 使用标题的文本内容测试从 apage 到 bpage 的导航。

基于https://testing-library.com/docs/example-reach-router

renderwithRouter.js

export default function renderWithRouter(ui, route = "/") {
  let source = createMemorySource(route);
  let history = createHistory(source);

  return {
    ...render(<LocationProvider history={history}>{ui}</LocationProvider>),
    history
  };
}

我的导航测试

应用程序.test.js

test('click navigates to b page', async () => {


  const { getByRole  } = renderWithRouter(<App />,  '/apage')

  fireEvent.click(getByRole("button"));

  await wait(() => {
    expect(getByRole('heading')).toHaveTextContent(/b page/i)
  });

});

未能给予

 Expected element to have text content:
      /b page/i
    Received:
      A Page

我如何测试这个导航?

4

2 回答 2

1

只需模拟 @reach/router 导航功能

import { navigate } from '@reach/router'
import * as React from 'react'
import { render, fireEvent } from 'react-testing-library'
import PageA from './PageA'

jest.mock('@reach/router', () => ({
  navigate: jest.fn(),
}))

describe('Page A', () => {
  it('Should navigate from Page A to Page B', () => {
    const { getByText } = render(<Page A />)
    fireEvent.click(getByText(/Sign In/i))
    expect(navigate).toHaveBeenCalledTimes(1)
    expect(navigate).toHaveBeenCalledWith('/bpage')
  })
})

我们相信,如果使用正确路径调用的导航函数将导航到页面 B, 例如此处

于 2021-04-02T07:48:15.423 回答
0

我有同样的问题。我使用的一个解决方法是模拟@reach-router 并断言它的导航功能被调用。在测试期间历史不会改变,但它会在应用程序上运行。不知道是什么导致了问题的开始。抱歉,我无法提供更多帮助。这是一个例子。

import {navigate} from '@reach/router'
import {waitFor, act} from '@testing-library/react'
import MagicUser from '@testing-library/user-event'
import {ValidUser} from '@test-utils/fixtures/user'
import {Routes} from '@utils/routes'
import {renderAuthForm} from './_utils'

const {username, password} = ValidUser
jest.mock('../../api', () => ({
  AuthFormApi: {
    login: jest.fn(() => Promise.resolve({user: {username}})),
    register: jest.fn(() => Promise.resolve({user: {username}})),
  },
}))

jest.mock('@reach/router', () => ({
  navigate: jest.fn(),
}))

describe('Successful user login', () => {
  describe('submitting the form', () => {
    it('navigates to the home page and adds user to local storage', async () => {
      const {getByRole} = renderAuthForm({
        username,
        password,
      })
      const submitButton = getByRole('button')
      await act(async () => {
        MagicUser.click(submitButton)
        await waitFor(() => {
          expect(navigate).toHaveBeenCalledWith(Routes.Home)
          expect(navigate).toHaveBeenCalledTimes(1)
        })
      })
    })
  })
})



于 2020-07-02T21:54:24.313 回答