I am writing an end-to-end test for a website using Cypress and would like to make an API POST request to authenticate a user.
I have been able to make a request that sends back a 200 response code with an appropriate jwt.
Here is a code snippet of what the request looks like:
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: 'https://api.website.com/api/login',
body: {
email: "xxx",
password: "xxx"
}
}).then((resp) => {
window.localStorage.setItem('jwt', resp.body.token)
// console.log(resp.body.token)
cy.log(resp)
})
cy.visit('/')
Here is an image of the Cypress test output: Cypress test
Here is an image of the Chrome console, showing a successful response code: Chrome console
After reading the Cypress command log, I noticed that the white circle indicates the request was unable to reach the server (the request was stubbed). What are the possible reasons for this happening?
Thanks in advance!
Update
I have managed to resolve my issue. The request was working however, I was not setting the right data in local storage in order to authenticate. After using the Google Chrome Developer tools, I found that both the auth._token.local and auth.refresh_token.local needed to be set after the request. I have attached the code snippet below to help anyone who comes across a similar issue. Thanks.
cy.request({
method: 'POST',
url: 'http://127.0.0.1:8000/api/login',
body: {
email: "email",
password: "password",
}
}).then((resp) => {
localStorage.setItem('auth._token.local', 'Bearer ' + resp.body.token)
localStorage.setItem('auth._refresh_token.local', false)
});
cy.visit('/');