如何用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);
});
推荐答案
对于我的情况我使用了这个 Github问题
for my case I used the answer of this Github issue
jest.mock('uuid/v4', (): () => number => {
let value = 0;
return () => value++;
});
这篇关于如何用Jest模拟uuid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!