[英]Test set cookies function with Jest
Does someone knows how can I test this function in Jest?有人知道如何在 Jest 中测试此功能吗? I don't have any ideas at this moment, maybe I need to mock Cookies ?我目前没有任何想法,也许我需要模拟 Cookies ?
import Cookies from "js-cookie";
import { v4 as uuidv4 } from "uuid";
const setUserCookie = () => {
if (!Cookies.get("UserToken")) {
Cookies.set("UserToken", uuidv4(), { expires: 10 });
}
};
export default setUserCookie;
I tried this for now, but I don't know if this is correct, I don't think it tests the functionality of my function:我现在尝试了这个,但我不知道这是否正确,我认为它不会测试我的函数的功能:
import Cookies from 'js-cookie';
import setCookie from './setCookie';
describe("setCookie", () => {
it("should set cookie", () => {
const mockSet = jest.fn();
Cookies.set = mockSet;
Cookies.set('testCookie', 'testValue');
setCookie()
expect(mockSet).toBeCalled();
});
});
Best way to test this is to utilize the actual logic, so I would change your test to the following:对此进行测试的最佳方法是利用实际逻辑,因此我会将您的测试更改为以下内容:
it("should set cookie", () => {
// execute actual logic
setCookie();
// retrieve the result
const resultCookie = Cookies.get();
// expects here
expect(resultCookie["UserToken"]).toBeTruthy();
// expects for other values here...
});
To note, uuidv4()
will generate a new value for every new test run, meaning that you cannot expect the same value for the "UserToken"
property.需要注意的是, uuidv4()
将为每次新的测试运行生成一个新值,这意味着您不能期望"UserToken"
属性具有相同的值。 Instead, you can use the following approach to tackle this problem:相反,您可以使用以下方法来解决此问题:
First set up a spy for it:首先为它设置一个间谍:
import { v4 as uuidv4 } from "uuid";
jest.mock('uuid');
Then add its mock implementation with the expected result into the unit test:然后将其具有预期结果的模拟实现添加到单元测试中:
const expectedUUIDV4 = 'testId';
uuidv4.mockImplementation(() => expectedUUIDV4);
// then expecting that in the result
expect(resultCookie["UserToken"]).toEqual(expectedUUIDV4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.