Code Your Greens

Mock Functions

Getting started

Let's make a simple file called greeter.ts that we want to mock:

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

Mock the entire file

Inside greeter.test.ts we can now mock the greeter.ts file:

jest.mock('./greeter')
it('should use the default mock implementation', () => {
expect(hello()).toBeUndefined()
})

This replaces the implementation of every function inside greeter.ts with a mock function created using jest.fn under the hood.

By default the mock functions will return undefined when called.

Spy on a named reference

Here's how to create a named reference to a mocked function:

const mockHello = hello as jest.Mock<any>
it('should detect it has been called', () => {
hello()
expect(mockHello).toHaveBeenCalled.times(1)
})

// jest.spyOn???

We can't spy on a function on its own:

// Matcher error: received value must be a mock or spy function
expect(hello).toHaveBeenCalled()

Now we can spy on whether our mock function was called from inside our test.

Provide a mock implementation

mockHello.mockImplementation(() => 'hello jest')
it('should use the mock implementation', () => {
expect(hello()).toEqual('hello jest')
})

Provide the actual implementation

What if we want to mock everything in the file, but use the actual implementation for one or two of the functions?

mockHello.mockImplementation(() => jest.requireActual('./greeter').hello)
it('should use the actual implementation', () => {
expect(hello()).toEqual('hello world')
})