javascript-如何用Jest模拟uuid
作者:互联网
因此,在寻找问题的答案时,我发现了该帖子:Jest: How to globally mock node-uuid (or any other imported module)
我已经尝试了答案,但似乎无法正确使用它,因为它给了我未定义的错误.我是测试领域的新手,所以请原谅任何重大错误:
这是我的第一个方法
const mockF = jest.mock('uuid');
mockF.mockReturnValue('12345789');
但是它无法识别功能.
“mockF.mockReturnValue is not a function” among others I tried.
然后我尝试按照帖子的建议进行手动模拟,但似乎无法使其正常工作,您能帮我吗?谢谢
这是整个测试是否有帮助:
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);
});
解决方法:
通过使用嘲笑模仿它.
import uuid from 'uuid/v4';
jest.mock('uuid/v4');
describe('mock uuid', () => {
it('should return testid }', () => {
uuid.mockImplementation(() => 'testid');
...
});
});
确保正确导入uuid(使用正确的版本参考,例如v4,v3 …)
标签:javascript,jestjs,uuid 来源: https://codeday.me/bug/20191011/1889171.html