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 { SomeClass } from './some-file'; // Mock the uuid module and v4 method jest.mock('uuid', () => ({ v4: () => 'hjhj87878' })); describe('Test Case', () => { let sut; beforeEach(() => { sut = new SomeClass(); }); test('My Test', () => { expect(sut.returnUuid()).toReturn('hjhj87878'); }); });
For reference, our SomeClass
implementation looks like this:
import { v4 as uuidv4 } from 'uuid'; export class SomeClass { returnUuid() { return uuidv4(); } }
To explain what we are doing here, we will use bullet points:
- The class we want to test is importing the
v4
function which generates our guids from theuuid
package - We have a method called
returnUuid
which calls the function and returns the generated guid - Inside of our test file, we mock the
v4
function inside of the uuid package by re-implementing it and returning a mocked value we can test for - Our test case checks this mocked value is what is returned
It is worth noting that this article previously detailed how you can mock the uuid package using jest.spyOn, however, some changes to the uuid package meant that older method of using spies to mock functions no longer works.