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);
    });

Answers:

Answer

Mock it by using mockImplementation.

import uuid from 'uuid/v4';
jest.mock('uuid/v4');

describe('mock uuid', () => {
  it('should return testid }', () => {
    uuid.mockImplementation(() => 'testid');
    ...
  });  
});

Make sure you import uuid correctly (with correct version reference e.g. v4, v3...)

Answer

Assuming the following test file, you can use the jest.spyOn call to mock out uuid.

Test.spec.js

import uuid from 'uuid';
import testTarget from './testTarget';

describe('mock uuid', () => {
  it('should return testid }', () => {
    // Arrange
    const anonymousId = 'testid';
    const v1Spy = jest.spyOn(uuid, 'v1').mockReturnValue(anonymousId);

    // Act
    const result = testTarget();

    // Assert
    expect(result).toEqual(anonymousId);
    expect(v1Spy).toHaveBeenCalledTimes(1);
  });  
});

testTarget.js

import uuid from 'uuid';
export default function() {
   return uuid.v1();
}
Answer

for my case I used the answer of this Github issue

jest.mock('uuid/v4', (): () => number => {
 let value = 0;
 return () => value++;
});
Answer
import uuid from 'uuid'

describe('some test', () => {
  it('some test 1', () => {
     const uuidMock = jest.spyOn(uuid, 'v4').mockReturnValue('123434-test-id-dummy');

     // expect(uuidMock).toHaveBeenCalledTimes(<number of times called>);

  })
})
Answer

As per this answer: How do I write test case for a function which uses uuid using jest?

You can use jest.mock inorder to mock the import of uuid, like that:

const uuidMock = jest.fn().mockImplementation(() => {
    return 'my-none-unique-uuid';
});
jest.mock('uuid', () => {
    return uuidMock;
});

The only caveat of that approach is that you need to apply the mock in the test file before you are importing your real file.

Then you will even able to assert on the mock.

Answer

It's really well explained in the documentation, but in general you can:

const mockF = jest.fn().mockReturnValue('12345789');

or

import uuid from 'uuid';
jest.mock('uuid', () => 
    jest.fn().mockReturnValue('12345789');
);
Answer

Hopefully the following two examples will be helpful.

Say you need a JS module whose sole resposibility is to generate UUIDs. Taking a TDD approach we start with an assertion and eventually see we need some UUIDGenerator with some method to return UUIDs:

it('should generate UUID', () => {
    const myUUID = UUIDGenerator.nextUUID();
    expect(myUUID).toEqual('some-short-v4-uuid-0');
});

The test, shapes UUIDGenerator.ts into the following code:

import {v4 as uuidv4} from 'uuid';
const UUIDGenerator = {
  storeUUID(): string {
    return uuidv4();
  }
};
export default UUIDGenerator;

Now we want to mock UUIDGenerator's dependency on the uuid module. We can do this by Calling jest.mock() with the module factory parameter as documented on jestjs.io. We can now simply describe how jest should behave,

jest.mock('uuid',() => ({
    v4: () => 'some-short-v4-uuid-0'
}));
describe('UUIDGenerator', () => { 
    // it block from above
});

You should now see you test passing.

The other alternative is to create some uuid.ts somewhere in your project:

import {v4 as uuidv4} from 'uuid';
export default uuidv4;

and import it in UUIDGenerator.ts:

import uuidv4 from '../uuid';

in this case, you should be able to mock your uuid.ts. I placed mine in the parent directory (relative to UUIDGenerator.ts) so you can see an example on how to find it when not in the same directory.

jest.mock('../uuid',
  () => jest.fn(() => '1-234-5678')
);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.