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);
});
Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.
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...)
This worked for me. In my case I only wanted to verify that the function was called rather than asserting on a specific value.
import * as uuid from 'uuid';
jest.mock('uuid');
const uuidSpy = jest.spyOn(uuid, 'v4');
// in a test block
expect(uuidSpy).toHaveBeenCalledTimes(1);
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.
for my case I used the answer of this Github issue
jest.mock('uuid/v4', () => {
let value = 0;
return () => value++;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With