Code Your Greens

Mock ES6 Modules

Mock Default Exports

Let's add a default export to our greeter.ts file:

export const hello = (): string => 'hello world'
const goodbye = (): string => 'goodbye world'
export default goodbye

Here's how we provide a mock implementation for the default export:

jest.mock('./greeter', () => ({
__esModule: true,
default: () => 'goodbye jest'
}))

This works because jest.mock accepts a function that returns a mocked module instead as its second argument.

Use a named reference

If you need a named reference to spy on, or give to different implementations of the default export throughout your test file, here's how to do it:

const mockGoodbye = jest.fn()
jest.mock('./greeter', () => ({
__esModule: true,
default: () => mockGoodbye()
}))

Mock default and named exports

const mockHello = jest.fn()
jest.mock('./greeter', () => ({
__esModule: true,
default: () => 'goodbye jest',
hello: () => mockHello()
}))

Use the actual implementation

jest.mock('./greeter', () => ({
__esModule: true,
default: jest.requireActual('./greeter').default
}))

Only mock certain functions

What if you want to use the actual implementation for everything, except for one or two things which you need to mock?

jest.mock('./greeter', () => {
const funcs = jest.requireActual('./greeter')
return {
__esModule: true,
default: jest.fn,
...funcs
}
})
// Inside test body
expect(hello()).toEqual('hello world')

Unfortunately you can't spread the jest.requireActual declaration directly inside the return body, you have to assign it to an intermediate variable.