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
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
}
})