Jest Mock module per test

后端 未结 4 1436
天命终不由人
天命终不由人 2020-12-13 02:25

I am quite confused with mocking in Jest an how to unit test the implementations. The thing is i want to mock different expected behaviours.

Is there any way to ach

4条回答
  •  -上瘾入骨i
    2020-12-13 02:42

    I use the following pattern:

    'use strict'
    
    const packageToMock = require('../path')
    
    jest.mock('../path')
    jest.mock('../../../../../../lib/dmp.db')
    
    beforeEach(() => {
      packageToMock.methodToMock.mockReset()
    })
    
    describe('test suite', () => {
      test('test1', () => {
        packageToMock.methodToMock.mockResolvedValue('some value')
        expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
    
      })
      test('test2', () => {
        packageToMock.methodToMock.mockResolvedValue('another value')
        expect(theThingToTest.someAction().type).toBe(types.OTHER_TYPE)
      })
    })
    

    Explanation:

    You mock the class you are trying to use on test suite level, make sure the mock is reset before each test and for every test you use mockResolveValue to describe what will be return when mock is returned

提交回复
热议问题