How To Mock uuid In Jest

When it comes to mocking dependencies in Jest, it couldn’t be easier. You can create an actual mock module that gets loaded in place of the dependency in your app or you can do it manually by mocking the implementation or module.

import uuid from 'uuid';
import { SomeClass } from './some-file'; 

describe('Test Case', () => {
    let sut;

    beforeEach(() => {
        sut = new SomeClass();
    });

    test('My Test', () => {
        jest.spyOn(uuid, 'v4').mockReturnValue('hjhj87878');

        expect(sut.returnUuid()).toReturn('hjhj87878');
    });

});

We need to import the library that we want to mock a specific method for, in this case it is the uuid library and the v4 method specifically. Inside of our test case we spy on the uuid class and v4 method.

We are assuming in this example that our returnUuid method is calling the v4 method in the uuid package to get a random guid. The above allows us to override the implementation on a test-by-test basis and choose what value is returned.

Leave a Reply

Your email address will not be published. Required fields are marked *