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

124
Visualizações
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 à 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