如何使用Jest

时间:2018-07-17 13:51:33

标签: javascript jestjs uuid

因此,在寻找问题的答案时,我发现了这篇文章:Jest: How to globally mock node-uuid (or any other imported module)

我已经尝试了答案,但似乎无法正确使用它,因为它给了我未定义的错误。我是测试领域的新手,所以请原谅任何重大错误:

这是我的第一个方法

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

11 个答案:

答案 0 :(得分:6)

这对我有用。就我而言,我只想验证函数是否被调用,而不是对特定值进行断言。

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

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

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

答案 1 :(得分:2)

希望以下两个示例会有所帮助。

假设您需要一个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模块的依赖性。我们可以通过on jestjs.io中所述的带有模块工厂参数的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')
);

答案 2 :(得分:1)

假设以下测试文件,您可以使用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();
}

答案 3 :(得分:1)

对于我来说,我使用了此Github issue

的答案
jest.mock('uuid/v4', (): () => number => {
 let value = 0;
 return () => value++;
});

答案 4 :(得分:0)

使用mockImplementation模拟它。

import uuid from 'uuid/v4';
jest.mock('uuid/v4');

describe('mock uuid', () => {
  it('should return testid }', () => {
    uuid.mockImplementation(() => 'testid');
    ...
  });  
});

确保您正确import uuid (带有正确的版本参考,例如v4,v3 ...)

答案 5 :(得分:0)

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

  })
})

答案 6 :(得分:0)

根据此答案:How do I write test case for a function which uses uuid using jest?

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

const uuidMock = jest.fn().mockImplementation(() => {
    return 'my-none-unique-uuid';
});
jest.mock('uuid', () => {
    return uuidMock;
});

该方法的唯一警告是,您需要在导入真实文件之前在测试文件中应用模拟

然后,您甚至可以对模拟进行断言。

答案 7 :(得分:0)

这对我有用

import { v1 as uuidv1 } from 'uuid';

jest.mock('uuid');


... # (somewhere on your test suite)

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

答案 8 :(得分:0)

这对我有用(我正在使用打字稿,如果不是,您可以删除 as blablabla):

jest.mock('uuid', () => ({
  v4: jest.fn(),
}));
const mockUuid = require('uuid') as { v4: jest.Mock<string, []> };

beforeEach(() => {
  mockUuid.v4.mockImplementationOnce(
    () => 'your-mocked-id',
  );
});

https://github.com/facebook/jest/issues/2172#issuecomment-756921887

答案 9 :(得分:0)

如果将 jest.mock('uuid') 放在错误的范围内,可能会出现问题。

这对我来说正确

import * as uuid from 'uuid';
jest.mock('uuid');
describe('utils', () => {
    it('test', () => {
        jest.spyOn(uuid, 'v4').mockReturnValue('mockedValue')
    });
});

这是不正确的

import * as uuid from 'uuid';
describe('utils', () => {
    it('test', () => {
        jest.mock('uuid');
        jest.spyOn(uuid, 'v4').mockReturnValue('mockedValue')
    });
});

答案 10 :(得分:-1)

documentation中对此进行了很好的解释,但是通常您可以:

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

import uuid from 'uuid';
jest.mock('uuid', () => 
    jest.fn().mockReturnValue('12345789');
);
相关问题