jest.mock(): How to mock ES6 class default import using factory parameter

前端 未结 3 1196
梦如初夏
梦如初夏 2020-12-25 11:30

Mocking ES6 class imports

I\'d like to mock my ES6 class imports within my test files.

If the class being mocked has multiple consumers, it may make sense

3条回答
  •  甜味超标
    2020-12-25 12:10

    If you are still getting TypeError: ...default is not a constructor and are using TypeScript keep reading.

    TypeScript is transpiling your ts file and your module is likely being imported using ES2015s import. const soundPlayer = require('./sound-player'). Therefore creating an instance of the class that was exported as a default will look like this: new soundPlayer.default(). However if you are mocking the class as suggested by the documentation.

    jest.mock('./sound-player', () => {
      return jest.fn().mockImplementation(() => {
        return { playSoundFile: mockPlaySoundFile };
      });
    });
    

    You will get the same error because soundPlayer.default does not point to a function. Your mock has to return an object which has a property default that points to a function.

    jest.mock('./sound-player', () => {
        return {
            default: jest.fn().mockImplementation(() => {
                return {
                    playSoundFile: mockPlaySoundFile 
                }   
            })
        }
    })
    

    For named imports, like import { OAuth2 } from './oauth', replace default with imported module name, OAuth2 in this example:

    jest.mock('./oauth', () => {
        return {
            OAuth2: ... // mock here
        }
    })
    

提交回复
热议问题