我是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]


我该如何解决这个问题?

最佳答案

useAxios挂钩返回一个数组,而您的mockImplementation返回一个Promise。

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
  }
]);

09-20 19:35