Javascript 如何开玩笑地模仿uuid

Javascript 如何开玩笑地模仿uuid,javascript,jestjs,uuid,Javascript,Jestjs,Uuid,因此,在我寻找问题答案的过程中,我发现了以下帖子: 我已经尝试过这个答案,但我似乎不能正确地使用它,因为它给了我一个未定义的错误。我是测试现场的新手,因此请原谅任何重大错误: 这是我的第一个方法 const mockF = jest.mock('uuid'); mockF.mockReturnValue('12345789'); 但它无法识别这些功能 “mockF.mockReturnValue不是一个函数”以及其他我尝试过的函数 然后,我试着按照帖子的建议手动模拟,但似乎无法让它工作,

因此,在我寻找问题答案的过程中,我发现了以下帖子:

我已经尝试过这个答案,但我似乎不能正确地使用它,因为它给了我一个未定义的错误。我是测试现场的新手,因此请原谅任何重大错误:

这是我的第一个方法

const mockF = jest.mock('uuid'); 

mockF.mockReturnValue('12345789'); 
但它无法识别这些功能

“mockF.mockReturnValue不是一个函数”以及其他我尝试过的函数

然后,我试着按照帖子的建议手动模拟,但似乎无法让它工作,你能帮我吗?谢谢

以下是整个测试,如果有帮助的话:

    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);
    });

在中有很好的解释,但一般来说,您可以:

const mockF = jest.fn().mockReturnValue('12345789');


假设有以下测试文件,您可以使用jest.spyOn调用模拟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();
}

在我的案例中,我使用了这个问题的答案


使用
mockImplementation
模拟它

从“uuid/v4”导入uuid;
笑话模拟('uuid/v4');
描述('mock uuid',()=>{
它('应该返回testid}',()=>{
uuid.mockImplementation(()=>'testid');
...
});  
});
确保正确导入uuid(使用正确的版本参考,如v4、v3…)
从“uuid”导入uuid
描述('一些测试',()=>{
它('一些测试1',()=>{
const uuidMock=jest.spyOn(uuid,'v4').mockReturnValue('123434-test-id-dummy');
//expect(uuidMock).toHaveBeenCalledTimes();
})
})
根据此答案:

您可以使用jest.mock来模拟uuid的导入,如下所示:

const uuidMock = jest.fn().mockImplementation(() => {
    return 'my-none-unique-uuid';
});
jest.mock('uuid', () => {
    return uuidMock;
});
该方法的唯一警告是,在导入真实文件之前,需要在测试文件中应用模拟


然后您甚至可以在mock上断言。

希望下面的两个示例会有所帮助

假设您需要一个JS模块,其唯一职责是生成UUID。 采用TDD方法,我们从一个断言开始,最终看到我们需要一些
UUIDGenerator
和一些返回uuid的方法:

it('should generate UUID', () => {
    const myUUID = UUIDGenerator.nextUUID();
    expect(myUUID).toEqual('some-short-v4-uuid-0');
});
测试将
UUIDGenerator.ts
塑造成以下代码:

import {v4 as uuidv4} from 'uuid';
const UUIDGenerator = {
  storeUUID(): string {
    return uuidv4();
  }
};
export default UUIDGenerator;
现在我们要模拟
UUIDGenerator
对uuid模块的依赖关系。我们可以通过调用jest.mock()和文档中的模块工厂参数来实现这一点。我们现在可以简单地描述笑话的行为

jest.mock('uuid',() => ({
    v4: () => 'some-short-v4-uuid-0'
}));
describe('UUIDGenerator', () => { 
    // it block from above
});
您现在应该看到您通过了测试

另一种选择是在项目中的某个地方创建一些
uuid.ts

import {v4 as uuidv4} from 'uuid';
export default uuidv4;
并将其导入
UUIDGenerator.ts

import uuidv4 from '../uuid';
在这种情况下,您应该能够模拟
uuid.ts
。我将我的放在父目录中(相对于
UUIDGenerator.ts
),这样您就可以看到一个示例,说明当不在同一目录中时如何查找它

jest.mock('../uuid',
  () => jest.fn(() => '1-234-5678')
);
这对我有用

import { v1 as uuidv1 } from 'uuid';

jest.mock('uuid');


... # (somewhere on your test suite)

uuidv1.mockImplementationOnce(() => {
  return 'uuid-123';
});

这对我有用。在我的例子中,我只想验证函数是否被调用,而不是断言一个特定的值

import * as uuid from 'uuid';
jest.mock('uuid');

const uuidSpy = jest.spyOn(uuid, 'v4');

// in a test block
expect(uuidSpy).toHaveBeenCalledTimes(1);

Does
jest.mock('uuid',()=>jest.fn(()=>1')为你工作?不幸的是我终于解决了!感谢所有的帮助,问题是我在一个特定的测试中,而不是在一个整体中,做了jest.mock和require。抱歉给您添麻烦,再次感谢Hanks,但我仍然收到一个未定义的错误:s其他测试通过,除了这一个,所以错误就在UUID上。如果我发布整个测试,会有帮助吗?请注意,包维护人员指出,此导入方法可能不推荐。^如果是,您需要运行
import{v4}来自“uuid”
的意思是,然后您模拟该函数,我得到了一个错误
无法窥视原语值;未定义给定值
:/I按照示例中提供的方式执行操作,并出现此错误:类型“v4”上不存在属性“mockImplementation”。@EA0906是否为TS错误?如果是这样的话,我在这里找到了一个解决方案:当我搜索jasmine测试时,谷歌没有合作,对于那些也在这里登陆的人:
import*作为“uuid”中的uuidspyOn(uuid,'v4')。和.returnValue('test-id')
@EA0906对于您的特定问题,您需要使用
const uuidVX=require('uuid/vX')
而不是
import
。然后你可以调用它的
mockImplementation
。虽然这段代码可以回答这个问题,但最好在不介绍其他代码的情况下解释它是如何解决问题的,以及为什么要使用它。从长远来看,仅代码的答案没有用处。uuid/v4返回一个字符串。此外,可以为mock实现重写返回jest.fn()。
jest.mock('../uuid',
  () => jest.fn(() => '1-234-5678')
);
import { v1 as uuidv1 } from 'uuid';

jest.mock('uuid');


... # (somewhere on your test suite)

uuidv1.mockImplementationOnce(() => {
  return 'uuid-123';
});
import * as uuid from 'uuid';
jest.mock('uuid');

const uuidSpy = jest.spyOn(uuid, 'v4');

// in a test block
expect(uuidSpy).toHaveBeenCalledTimes(1);