You’re ****ing Kidding Me

There seems to be a lot of voodoo on the internet about how to mock a class using jest in TypeScript.

After a lot of wasted googling, I’ve got a working solution.

In this project, I have an api which will create a new object of LeadService in order to perform some function or other. I want to completely mock the LeadService so that I can control it for testing.

Here’s a snippet of the test that’s presently green:

import LeadService from '../../src/leads/LeadService';
import { handler } from '@/leads/api';

jest.mock('../../src/leads/LeadService');

const mocked = LeadService as jest.MockedClass<typeof LeadService>;

describe('Lead service api', () => {
    beforeEach(() => {
        mocked.mockClear();
    });


    ...
        expect(mocked.mock.instances[0].store).toHaveBeenCalledWith(
            expect.anything(),
            '7e0c48ee-e92a-4284-912f-1ed8fd91ce98',
        );

The above shows how to use jest.mock to automatically replace everything in the module. There’s jest.MockedClass to provide a handy mocked object for controlling the mock.

The use of mockClear in beforeEach resets the mock each time.

Finally, the expect function uses toHaveBeenCalledWith and provides it with a wildcard matcher – expect.anything to ignore the first parameter, in this case an unpredictable timestamp.

It works well… but getting to a complete set is very frustrating!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s