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()
    })
  • 相关阅读:
    IOS 使用动态库(dylib)和动态加载framework
    iOS 开发者应该知道的 ARM 结构
    解惑好文:移动端H5页面高清多屏适配方案
    js 单例模式的实现方式----闭包和构造函数内部判断
    解决express video 手机无法播放的问题
    前后端通吃的单元测试---mocha
    swift-ios开发pod的使用(1)
    UI 自动化测试工具BackstopJS简介(1)
    阿里妈妈-RAP项目的实践(3)
    阿里妈妈-RAP项目的实践(2)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12877808.html
Copyright © 2011-2022 走看看