问题
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);
});
回答1:
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...)
回答2:
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();
}
回答3:
for my case I used the answer of this Github issue
jest.mock('uuid/v4', (): () => number => {
let value = 0;
return () => value++;
});
回答4:
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>);
})
})
回答5:
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');
);
来源:https://stackoverflow.com/questions/51383177/how-to-mock-uuid-with-jest