Jest Mock module per test

后端 未结 4 1434
天命终不由人
天命终不由人 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条回答
  • 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

    0 讨论(0)
  • 2020-12-13 02:42

    Andreas answer work well with functions, here is what I figured out using it:

    // You don't need to put import line after the mock.
    import {supportWebGL2} from '../utils/supportWebGL';
    
    
    // functions inside will be auto-mocked
    jest.mock('../utils/supportWebGL');
    const mocked_supportWebGL2 = supportWebGL2 as jest.MockedFunction<typeof supportWebGL2>;
    
    // Make sure it return to default between tests.
    beforeEach(() => {
      // set the default
      supportWebGL2.mockImplementation(() => true); 
    });
    
    it('display help message if no webGL2 support', () => {
      // only for one test
      supportWebGL2.mockImplementation(() => false);
    
      // ...
    });
    

    It won't work if your mocked module is not a function. I haven't been able to change the mock of an exported boolean for only one test :/. My advice, refactor to a function, or make another test file.

    export const supportWebGL2 = /* () => */ !!window.WebGL2RenderingContext;
    // This would give you: TypeError: mockImplementation is not a function
    
    0 讨论(0)
  • 2020-12-13 02:46

    You can mock with a spy and import the mocked module. In your test you set how the mock should behave using mockImplementation:

    jest.mock('the-package-to-mock', () => ({
      methodToMock: jest.fn()
    }));
    import {methodToMock} from 'the-package-to-mock'
    
    it('test1', () => {
      methodToMock.mockImplementation(() => 'someValue')
    })
    
    it('test2', () => {
       methodToMock.mockImplementation(() => 'anotherValue')
    })
    
    0 讨论(0)
  • 2020-12-13 02:46

    spyOn worked best for us. See previous answer:

    https://stackoverflow.com/a/54361996/1708297

    0 讨论(0)
提交回复
热议问题