繁体   English   中英

使用 Jest 测试设置 cookie 功能

[英]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"属性具有相同的值。 相反,您可以使用以下方法来解决此问题:

首先为它设置一个间谍:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM