I have a situation where I want to generate a JWT token in an intercept and return it in it's body. The problem is that in the payload of that token a value should be used from another intercept. This means that i can only generate the token during the interception.
const code = '1234567890ABCDEFGH';
let accessTokenSource, idTokenSource, accessToken, idToken;
cy.fixture('access.token.json').then((source) => (accessTokenSource = source));
cy.fixture('id.token.json').then((source) => (idTokenSource = source));
cy.intercept('https://****/authorize', (req) => {
const url = new URL(req.url);
idTokenSource.claims.nonce = url.searchParams.get('nonce');
req.redirect(`${Cypress.config().baseUrl}?code=${code}&state=${url.searchParams.get('state')}`);
});
cy.intercept('https://****/oauth/token', (req) => {
cy.task('generateToken', accessTokenSource).then((token) => (accessToken = token));
cy.task('generateToken', idTokenSource).then((token) => (idToken = token));
console.log('accessToken', accessToken);
console.log('idToken', idToken);
req.reply({
body: {
access_token: accessToken,
expires_in: 86400,
id_token: idToken,
scope: 'openid profile email',
token_type: 'Bearer',
},
headers: {
'content-type': 'application/json',
},
});
});
As you probably already thought, the accessToken and idToken are empty.
What should i change here to wait until the generateToken task is completed to use it in the req.reply?
p.s. I've already tried this, but it doesn't work:
cy.task('generateToken', accessTokenSource).as('generateAccessToken');
cy.task('generateToken', idTokenSource).as('generateIdToken');
cy.wait('@generateAccessToken').then((token) => (accessToken = token));
cy.wait('@generateIdToken').then((token) => (idToken = token));
console.log('accessToken', accessToken);
console.log('idToken', idToken);
p.s.2. The generateToken works just fine when I put it in the it() of the test.