用Jest测试set cookies功能



有人知道我如何在Jest中测试这个函数吗?我现在没有任何想法,也许我需要嘲笑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;

我现在试了一下,但我不知道这是否正确,我不认为它测试了我的函数的功能:

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

最好的测试方法是利用实际的逻辑,所以我将您的测试更改为以下内容:

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

需要注意的是,uuidv4()将为每次新的测试运行生成一个新值,这意味着您不能期望"UserToken"属性得到相同的值。相反,您可以使用以下方法来解决此问题:

首先为它设置一个间谍:

import { v4 as uuidv4 } from "uuid";
jest.mock('uuid');
然后将具有预期结果的模拟实现添加到单元测试中:
const expectedUUIDV4 = 'testId';
uuidv4.mockImplementation(() => expectedUUIDV4);
// then expecting that in the result
expect(resultCookie["UserToken"]).toEqual(expectedUUIDV4);

最新更新