如何使用gatsby.navigate函数编写一个开玩笑的单元测试?

时间:2019-07-08 18:35:51

标签: reactjs unit-testing jestjs gatsby react-testing-library

晚上,

我正在使用Gatsby构建客户端专用的应用程序。

我正在尝试为<Login />组件编写一些单元测试。

用户成功登录后,他们将被重定向到/ app /, 通过gatsby的导航功能进行编程

这是我到目前为止的测试:

import React from 'react'
import userEvent from '@testing-library/user-event'
import 'jest-dom/extend-expect'
import { navigate } from 'gatsby'
import {
    render,
    fireEvent,
    cleanup,
    act,
    wait
} from '~/__tests__/utils/wrapper'
import Login from '../index'

describe('<Login />', () => {

    afterEach(cleanup)

    it('should redirect to /app/ when the correct details are used', async () => {
        const { getByTestId, getByLabelText } = render(<Login />)
        const emailField = getByLabelText('Email address')
        const passwordField = getByTestId('password-input')

        act(() => {
            userEvent.type(emailField, 'test@email.com')
            userEvent.type(passwordField, 'password')
        })

        await wait()

        act(() => {
            fireEvent.click(getByTestId('login-submit'))
        })

        await wait()

        expect(navigate).toHaveBeenCalledTimes(1) // FAILS
        expect(navigate).toHaveBeenCalledWith('/app/') // FAILS
    })
})

我在这里关注了文档: https://www.gatsbyjs.org/docs/unit-testing/#3-useful-mocks-to-complete-your-testing-environment

我还向导出的对象中添加了navigate: jest.fn()

该组件正在运行,因此肯定与我的测试有关。

任何帮助,不胜感激

2 个答案:

答案 0 :(得分:0)

在此处查看文档:

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

我现在已经像这样包裹了组件​​

function renderWithRouter(
    ui,
    { route = '/', history = createHistory(createMemorySource(route)) } = {}
) {
    return {
        ...render(<LocationProvider history={history}>{ui}</LocationProvider>),
        // adding `history` to the returned utilities to allow us
        // to reference it in our tests (just try to avoid using
        // this to test implementation details).
        history
    }
}

还...

https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-link/src/tests/index.js

了解更多信息

答案 1 :(得分:0)

应在项目的根目录(/ src外部)中添加__mocks__/gatsby.js

您可以在此处模拟gatsby函数,包括navigate

一个例子:

// __mocks__/gatsby.js
const gatsby = jest.requireActual('gatsby');

module.exports = {
  ...gatsby,
  navigate: jest.fn(),
}

在测试中,您需要告诉玩笑者将此模拟与jest.mock('gatsby');一起使用。


或者,您可以在测试文件中进行模拟:

// __tests__/Component.jsx
jest.mock('gatsby', () => {
  const gatsby = jest.requireActual('gatsby');

  return {
    ...gatsby,
    navigate: jest.fn(),
  }
});