Search code examples
javascriptjestjsuuid

How to mock uuid with Jest


so on my search for an answer to my problem I found this post: Jest: How to globally mock node-uuid (or any other imported module)

I already tried the answer but I can't seem to use it properly, as it´s giving me an undefined error. I'm new to the testing scene so please excuse any major errors:

This was my first approach

const mockF = jest.mock('uuid'); 

mockF.mockReturnValue('12345789'); 

But it wouldn't recognize the functions.

"mockF.mockReturnValue is not a function" among others I tried.

Then I tried to manually mock as the post suggested but can' seem to make it work, can you help me? Thanks

Here's the entire test if it helps:

    const faker = require('faker');
    const storageUtils = require('../../storage/utils');
    const utils = require('../utils/generateFile');
    const { generateFileName } = storageUtils;
    const { file } = utils;

    test('should return a valid file name when provided the correct information', () => {
        // ARRANGE
        // create a scope
        const scope = {
            type: 'RECRUITER',
            _id: '987654321',
        };
        // establish what the expected name to be returned is
        const expectedName = 'r_987654321_123456789.png';

        jest.mock('uuid/v4', () => () => '123456789');

        // ACTION
        const received = generateFileName(file, scope);

        // ASSERT
        // expect the returned value to equal our expected one
        expect(received).toBe(expectedName);
    });

Solution

  • I figure I might as well add my solution here, for posterity. None of the above was exactly what I needed:

    jest.mock('uuid', () => ({ v4: () => '123456789' }));
    

    By the way, using a variable instead of '123456789' breaks it.

    This should be mocked where we have the imports and it does not require you to explicitely import uuid in your spec file.