I have been developing a few small projects using TypeScript in my new job and the experience is quite joyful. I always know JavaScript is quite a free style language but never expect it to become so organised and descriptive with the addition of TypeScript. But this is not the topic of this article today. This artciel is focusing on sharing some tips I learned from using Jest library and took me a while to find the answer on internet.

Mock a static method in Jest

It’s quite easy to mock a static method in Jest that you only need to import it and then replace the method with the mock function. A code example looks like this:

import {A} from "./a"

A.static_method = jest.fn()

Assert an exception thrown from an async method

You can’t directly use try catch to catch the exception thrown from an async method. Luckily, there is a way to support that in the Jest expect method.

await expect(asyncMethod()).rejects.toThrow{
    "the error message from new Error()"
}

Mock an imported class

In Jest, per the offical documentation, you can mock an imported class with this syntax:

jest.mock("./moduleA")

But the drawback is that you don’t have flexbility to assert the mocks. Jest provideds a way to customize it.

const mockedMethodA = jest.fn()
jest.mock("../src/portal/portal", () =>
    jest.fn().mockImplementation(() => ({
        methodA: mockedMethodA
    }))
);

describe("unit test", () => {
    it("should do st", async() => {
        //do something
    })
})

You pass a mocked jest function to the mock implementation of the class that is used in the logic code. This way can enable you to control the lifecycle of the mock as well as assert the information carried within it.

Note, mocks setup should always be placed outside the describe block.

Furthermore, if your file exports more than one class and you only want to mock one of them, you can use following trick to restore the implementation of the classes other than the one that needs to be mocked.

jest.mock("./multi-classes.ts", () => {
    const actualModule = jest.requireActual(
        "./multi-classes.ts"
    );

    return {
        ...actualModule,
        ClassToBeMocked: jest.fn().mockImplementation(() => ({
            getFn: jest.fn(),
        })),
    };
});