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

查看:142
本文介绍了如何为使用juid的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;
}

我将测试用例写为:

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.

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

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