I'm using cypress to test an api, and I've got an access_token parameter in the hash that I need to stick in the Authorization header for all requests.
In the example below, if I use the header directly in the request() call, everything works perfectly. If I move it into the interceptor, I get a 401/Unauthorized. What am I doing wrong?
cy.location('hash').then((hash) => {
// Extract access_token from hash
const params = new URLSearchParams(hash.replace('#', ''));
const accessToken = params.get('access_token');
cy.log(`Adding Authorization header: Bearer ${accessToken}`);
// Intercept all requests
cy.intercept('*', (req) => {
// Add Authorization header
if (accessToken) {
//req.headers['Authorization'] = `Bearer ${accessToken}`
}
req.continue()
}).as('auth');
cy.request({
url: '/v1/me',
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`
}
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body).to.have.property('email')
})
});
Seems like cy.request isn't intercepted by cy.intercept, which makes close to zero sense, but you can wrap fetch up, which IS handled by:
cy.wrap(null).then(async () => {
const response = await fetch('/v1/me')
const data = await response.json()
expect(data).to.have.property('email')
})
The fetch() call will trigger the intercept() call, which you can then use to apply auth headers, etc.