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.