Search code examples
google-authenticationcypresstwo-factor-authenticationgoogle-authenticator

Cypress generates outdated code for Google Authenticator


Starting cypress ui test between (20..30) or (50..60) second of the minute causes wrong Google 2 factor token generation. It generates prevoious token.

Here is my token generation function:

function getToken () {
  const totp = require('totp-generator');
  const token = totp('2CQQGPPYFE7JPJAX');
  return token;
}

Here is how i get token before using it:

let token = getToken()

It looks like the token is generated on the beginning of the test (even if the call is in the middle of the test), and token is outdated at the time of it's usage, because new period has started.


Solution

  • Does this work for you?

    Use promise function.

    describe('check the tokens', function() 
    {
    // on 25 seconds 
    it('Test first token ',()=> {
        cy.wait(25000).then(()=>{
            let token = getToken();
            console.log('first token: ' + token);
        })
    })
    // on 55 seconds 
    it('Test second token', ()=>{
        cy.wait(30000).then(()=>{
            let token = getToken();
            console.log('second token: '+ token);
        });
    })
    })
    
    function getToken () {
        const totp = require('totp-generator');
        const token = totp('2CQQGPPYFE7JPJAX');
        return token;
      }
    
    

    enter image description here