Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda