• 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 Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • How To Mock uuid In Jest
  • How To Decompile And Compile Android APK's On A Mac Using Apktool
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • Wild Natural Deodorant Review

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz