Cypress: How to await a `cy.task` in a `cy.intercept`

Viewed 671

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.

1 Answers

I've created a workaround by not using the plugin anymore but directly executing the sign function.

On top of the cypress test file:

import jwt from 'jsonwebtoken';

const generateToken = function (privateKey, options) {
  return jwt.sign(options.claims, privateKey, { algorithm: 'RS256', expiresIn: options.expires, issuer: options.issuer });
};

Start of the test:

let authCode, privateKey, accessTokenSource, idTokenSource, accessToken, idToken;

authCode = Cypress.env('authCode');
cy.readFile(Cypress.env('jwtPrivateKey')).then((key) => (privateKey = key));
cy.fixture('access.token.json').then((source) => (accessTokenSource = source));
cy.fixture('id.token.json').then((source) => (idTokenSource = source));

Intercept:

cy.intercept('https://***/oauth/token', (req) => {
  const params = new URLSearchParams(req.body);
  expect(params.get('code')).to.equal(authCode);

  accessToken = generateToken(privateKey, accessTokenSource);
  idToken = generateToken(privateKey, idTokenSource);

  req.reply({
    body: {
      access_token: accessToken,
      expires_in: 86400,
      id_token: idToken,
      scope: 'openid profile email',
      token_type: 'Bearer',
    },
    headers: {
      'content-type': 'application/json',
    },
  });
});
Related