有人知道如何在 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();
});
});
uj5u.com熱心網友回復:
對此進行測驗的最佳方法是利用實際邏輯,因此我會將您的測驗更改為以下內容:
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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475364.html
標籤:javascript 测试 开玩笑的 js-cookie
上一篇:如何將多個2D測驗資料陣列構建到屬性檔案中并為我的測驗讀取它們?
下一篇:如何讓硒打開我的電子應用程式?
