[React Testing] Using __mocks__ to mock the promise based API

Folder structure:

| __mocks__

    | api 

       | pet.js

| src

   | api 

      | pet.js

__mocks__/api/pet.js

// __mocks__/api/pet.js

import { readFileSync } from 'fs'
import path from 'path'
import { act } from '@testing-library/react'

const breeds = [{ name: 'apple' }, { name: 'meat' }, { name: 'drink' }]
const doggos = JSON.parse(
  readFileSync(path.join(__dirname), 'res.json').toString(),
)

export const ANIMALS = ['dog', 'cat', 'bird']
export const _breeds = breeds
export const _dogs = doggos.animals

const mock = {
  // mock the breeds function
  breeds: jest.fn(() => {
    return {
      // breeds function is promise based
      // should have then function on it
      // act: info react we have done things need to be udpated
      then: (callback) => act(() => callback({ breeds })),
    }
  }),
  animals: jest.fn(() => {
    return {
      then: (callbacka) => act(() => callback(doggs)),
    }
  }),
}

export default mock

Component test:

import React from 'react'
import { render, fireEvent } from '@testing-library/react'

import pet, { ANIMALS, _breeds, _dogs } from '@api/pet'
afterEach(() => {
  jest.clearAllMocks()
})

test('SearchParams', async () => {
  const { container, getByText, getByTestId } = render(<SearchParams />)
  const animalDropdown = getByTestId('use-dropdown-animal')
  expect(animalDropdown.children.length).toEqual(ANIMALS.length + 1)
  expect(pet.breeds).toHaveBeenCalled()

  const breedDropdown = getByTestId('use-dropdown-breed')
  expect(breedDropdown.children.length).toEqual(_breeds.length + 1)
  expect(pet.breeds).toHaveBeenCalled()

  const searchResult = getByTestId('search-results')
  expect(searchResult.textContent).toEqual('No pets found')
  fireEvent(getByText('Submit'), new MouseEvent('click'))
  expect(searchResult.children.length).toEqual(_dogs.length)

  // run jest -u will udpate the snapshot
  expect(container.firstChild).toMatchInlineSnapshot()
})
原文地址:https://www.cnblogs.com/Answer1215/p/12877808.html