使用 Jest 测试设置 cookies 功能

Test set cookies function with Jest

有人知道如何在 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" 属性 具有相同的值。相反,您可以使用以下方法来解决此问题:

先给它设置一个spy:

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