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()
    })
  • 相关阅读:
    oracle case when的使用方法
    php数字,字符,对象判断函数
    php is_dir 判断是否为目录
    mysql服务器查询慢原因分析与解决方法
    php生成html文件的多种方法介绍
    php mysql mysqli区别比较详解
    C++定时器用法(已经封装成类)
    获取远程计算机MAC
    批量获取远程计算机MAC
    c++封装日志类
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12877808.html
Copyright © 2011-2022 走看看