zoukankan      html  css  js  c++  java
  • [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()
    })
  • 相关阅读:
    课题论文之调研--贝叶斯网络
    Android开发--数据存储之数据库操作
    Android开发--数据存储之File文件存储
    ROS常用命令
    CMakeLists.txt实例运用(入门)
    乐视三合一奥比中光Orbbec Astra Pro在ROS中配置显示RGB、深度、IR图像的两种思路
    VTK显示CT图像视图
    手眼标定
    并联机器人位姿解算
    信息物理融合CPS
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12877808.html
Copyright © 2011-2022 走看看