如何使用 jest 为使用 uuid 的函数编写测试用例? [英] How do I write test case for a function which uses uuid using jest?

查看:34
本文介绍了如何使用 jest 为使用 uuid 的函数编写测试用例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jest 编写测试用例.我的一个函数使用 uuid,因此它不是纯函数.代码是这样的:

I'm using jest for writing test cases. One of my function uses uuid and due to which it is not a pure function. The code is something like this:

const myFunc = () => {
    const a = uuid();

    return a;
}

我正在编写我的测试用例:

I'm writing my test case as :

test('should return a unique id value', () => {
    const a = uuid();
    expect(myFunc()).toEqual(a);
});

显然它不会工作,因为它每次都会生成一个唯一的 ID.我如何为这样的函数编写测试用例.

Obviously it won't work as it will generate a unique Id every time. How can I write test case for such function.

我不想测试 uuid 函数,因为它总是会生成一个新的 id,而且它是一个已经在测试中的库函数.我想测试另一个使用 uuid 的函数,生成新对象并返回它.这个函数被其他一些函数使用等等,这让我无法测试任何一个,因为初始对象的 id 与我在测试时使用的 id 不同.

I don't want test the uuid function as it will always generate a new id and it is a library function which is already being tested. I want to test another function which uses uuid, generates new object and returns that. This function is used by some other function and so on which makes me not able to test any of that because the initial object has an id which is different that the id which I'm using while testing.

推荐答案

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

You can use jest.mock inorder to mock the import of uuid, like that:

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

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

The only caveat of that approach is that you need to apply the mock in the test file before you are importing your real file.

然后你甚至可以在模拟上断言.

Then you will even able to assert on the mock.

欲了解更多信息,请阅读 jest.mock.

For more info read jest.mock.

这篇关于如何使用 jest 为使用 uuid 的函数编写测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆