Как я могу издеваться над крючком useAx ios из топора ios с помощью Jest? (Ошибка: Uncaught [Ошибка типа: undefined не является функцией]) - PullRequest
0 голосов
/ 19 апреля 2020

Я новичок в Jest, и я хочу высмеять useAxios из axios-hooks, чтобы избежать фактического вызова службы. Это мой компонент:

import React from 'react'
import useAxios from 'axios-hooks'
import { Table, Space } from 'antd'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faEdit, faCalendar, faUserPlus } from '@fortawesome/free-solid-svg-icons'

const Projects = () => {
  const [{ data: projects, loading, error }] = useAxios(
    `${process.env.REACT_APP_API_URL}/projects/`
  )

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!</p>

  const columns = [
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: title => <a>{title}</a>
    },
    {
      title: 'Start Date',
      dataIndex: 'startDate',
      key: 'startDate'
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
      render: description => `${description.substring(0, 50)}...`
    },
    {
      title: 'Team',
      dataIndex: 'team',
      key: 'team'
    },
    {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <Space size='middle'>
          <FontAwesomeIcon icon={faEdit} />
          <FontAwesomeIcon icon={faCalendar} />
          <FontAwesomeIcon icon={faUserPlus} />
        </Space>
      )
    }
  ]

  return (
    <Table
      data-testid='project-table-id'
      columns={columns}
      dataSource={projects}
      pagination={false}
    />
  )
}

export default Projects

Это тест, который я выполняю:

import React from 'react'
import { render, cleanup } from '@testing-library/react'
import Projects from '../Projects'
import useAxios from 'axios-hooks'
jest.mock('axios-hooks')

describe('Projects component', () => {
  afterEach(cleanup)

  it('renders project table', async () => {
    const fakeResponse = [
      {
        title: 'Testing Project Alpha',
        startDate: '2020-04-18',
        description: 'This is just for testing',
        team: 'A, B, C'
      },
      {
        title: 'Testing Project Beta',
        startDate: '2020-04-19',
        description: 'This is just for testing too',
        team: 'X, Y, Z'
      }
    ]
    useAxios.mockImplementation(() => Promise.resolve({fakeResponse}))
    const { getByTestId } = render(<Projects />)
    expect(getByTestId('project-table-id')).not.toBeNull()
  })
})

Однако я получаю следующую ошибку:

Error: Uncaught [TypeError: undefined is not a function]

Как я могу решить эту проблему?

1 Ответ

1 голос
/ 19 апреля 2020

Хук useAxios возвращает массив, тогда как ваш mockImplementation возвращает Обещание.

const [{ data, loading, error }] = useAxios(/* ... */); // returns array

useAxios.mockImplementation(() => Promise.resolve({fakeResponse})) // returns Promise

Изменение mockImplementation для возврата массива, содержащего объект с одним, несколькими или всеми поля data/loading/error будут работать:

useAxios.mockImplementation(() => [
  {
    data: fakeResponse
  }
])

Так как реализация не высмеивает поведение useAxios (оно проверяет возвращаемое значение), вы можете использовать mockReturnValue вместо этого:

useAxios.mockReturnValue([
  {
    data: fakeResponse
  }
]);
...