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

119
Vistas
Jest mocking api and checking if localStorage.setItem is called

I have mocked my login api like this

const server = setupServer(
  rest.get(authenticationLogin, (req, res, ctx) => {
    return res(
      ctx.json({
        status: 200,
        data: {
          tenantKey: 'tenant',
          employeeDto: {
            firstName: 'firstname',
            lastName: 'lastname',
            token: 'tplem',
            role: 'role',
            id: 1,
            userName: 'username',
            designation: 'designation',
          },
        },
      }),
    )
  }),
)

And I have a test setup like this

test('should redirect to / when login successful', async () => {
    const setItem = jest.spyOn(Storage.prototype, 'setItem')

    userEvent.type(renderedScreen.getByPlaceholderText('Username'), 'testing')

    userEvent.click(renderedScreen.getByRole('button'))

    await waitFor(() => {
      // check if setItem is called to save to localStorage
      expect(setItem).toHaveBeenNthCalledWith(1, 'firstname')

      // check if a redirect happens meaning login was successful
      expect(history.location.pathname).toBe('/')
    })
  })

In the component file, the login function will save the response items to the localStorage

localStorage.setItem('employeeName', employeeName)
localStorage.setItem('employeeId', employeeId)
localStorage.setItem('userName', userName)
localStorage.setItem('role', role)
localStorage.setItem('tenantKey', tenantKeyFromResponse)
localStorage.setItem('token', token)
localStorage.setItem('designation', designation)

But somehow I am getting this error

expect(jest.fn()).toHaveBeenNthCalledWith(n, ...expected)

    n: 1
    Expected: "test"
    Received
    ->     1: "test", "test"
           2: "test", "test"

    Number of calls: 3

I don't even know where the strings 'test' are coming from. I am returning different values from the mock api.

The number of calls isn't even correct. It says in the log that it has been only called 3 times when in the login function it is called 7 times.

about 4 years ago · Juan Pablo Isaza
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