Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

391
Vistas
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();
  });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda