• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How To Mock uuid In Jest

Jest · April 25, 2020

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 the uuid 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.

Dwayne

Leave a ReplyCancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Handling Errors with the Fetch API
  • How To Get The Hash of A File In Node.js
  • Testing Event Listeners In Jest (Without Using A Library)
  • The Quad Cortex Desktop Editor is Finally Announced
  • How To Paginate An Array In Javascript

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz