• [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()
    })
  • 相关阅读:
    robot 如何定义用户关键字、变量
    appium 启动参数配置
    mock模拟接口返回数据
    jenkins 中邮件发送
    python中正则表达式
    python中操作数据库
    pytest和unittest中参数化如何做
    learnku社区分享
    FOR ALL ENTRIES IN的使用
    BAPI_DELIVERYPROCESSING_EXEC
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12877808.html
Copyright © 2020-2023  润新知