javascripttestingjestjsjs-cookie

Test set cookies function with Jest


Does someone knows how can I test this function in Jest? I don't have any ideas at this moment, maybe I need to mock 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();
  });
});

Solution

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