如何用 Jest 模拟 uuid [英] How to mock uuid with Jest
问题描述
所以在我寻找问题的答案时,我发现了这篇文章:Jest:如何全局模拟 node-uuid(或任何其他导入模块)
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:
这是我的第一个方法
const mockF = jest.mock('uuid');
mockF.mockReturnValue('12345789');
但它无法识别这些功能.
But it wouldn't recognize the functions.
mockF.mockReturnValue 不是函数"以及我尝试过的其他方法.
"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);
});
推荐答案
使用 mockImplementation
模拟它.
import uuid from 'uuid/v4';
jest.mock('uuid/v4');
describe('mock uuid', () => {
it('should return testid }', () => {
uuid.mockImplementation(() => 'testid');
...
});
});
确保您导入 uuid
正确(使用正确的版本参考,例如 v4、v3...)
这篇关于如何用 Jest 模拟 uuid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!