Hey there,
I’m trying to get cypress working with auth0-react
. I’ve been banging my head on this for a while so I can’t even find where I found the below code from.
I have this in my cypress commands.js
Cypress.Commands.add(
'login',
(username, password, appState = { targetUrl: '/' }) => {
cy.log(`Logging in as ${username}`);
const options = {
method: 'POST',
url: Cypress.env('auth_url'),
body: {
grant_type: 'password',
username: Cypress.env('auth_username'),
password: Cypress.env('auth_password'),
audience: Cypress.env('auth_audience'),
scope: 'openid profile email',
client_id: Cypress.env('auth_client_id'),
client_secret: Cypress.env('auth_client_secret'),
},
};
cy.request(options).then(({ body }) => {
const { access_token, expires_in, id_token } = body;
cy.server();
// intercept Auth0 request for token and return what we have
cy.route({
url: 'oauth/token',
method: 'POST',
response: {
access_token: access_token,
id_token: id_token,
scope: 'openid profile email',
expires_in: expires_in,
token_type: 'Bearer',
},
});
// Auth0 SPA SDK will check for value in cookie to get appState
// and validate nonce (which has been removed for simplicity)
const stateId = 'test';
cy.setCookie('auth0.is.authenticated', 'true');
cy.setCookie(
`a0.spajs.txs.${stateId}`,
encodeURIComponent(
JSON.stringify({
appState: appState,
scope: 'openid profile email',
audience: Cypress.env('auth_audience'),
redirect_uri: 'http://localhost:3000',
}),
),
).then(() => {
cy.visit(`/?code=test-code&state=${stateId}`, {
onBeforeLoad(win) {
delete win.fetch;
},
});
});
});
},
);
Cypress.Commands.overwrite('visit', (originalFn, url, options) => {
const opts = Object.assign({}, options, {
onBeforeLoad: (window, ...args) => {
window.fetch = null;
if (options.onBeforeLoad) {
return options.onBeforeLoad(window, ...args);
}
},
});
return originalFn(url, opts);
});
Cypress.on('window:before:load', (win) => {
delete win.fetch;
});
I have cypress.json:
{
"experimentalFetchPolyfill": true,
"baseUrl": "http://localhost:3000"
}
The problem seems to be that @auth0/auth0-react
is using fetch which isn’t caught by cy.route()
above, even if I frantically try to remove window.fetch
+ run experimentalFetchPolyfill
. I’ve also tried to do window.fetch = null
in the top of my index.js
.
Have anyone else gotten auth0-react to play nicely with cypress? Could you guide me through it?