Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

117
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!