Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

javascript - How to set variable and access from cypress framework

I am using cypress framework to test node app. I want to check variable is set to 'SUCCESS'. Intially it is set to 'FAILURE' but from cypress exec it is set to 'SUCCESS'. But when I invoke the function it is still 'FAILURE'. Can someone help me understand where I made it wrong.

cypresssupport eturnStatus.js

module.exports = function() {

    this.returnStatus = "FAILURE";

   this.SuccessMsg =  function() {
      cy.exec('echo hello',  { log: true, failOnNonZeroExit: false }).then((output) => {
                    this.returnValue = "SUCCESS";
                  
          });

   
   }
}

cypressintegrationcheckReturnValue.spec.js

let Status = require('../support/returnStatus');
let helper = new Status();

describe("Check return value", function(){
    it("should check latest value", function(){
        let reply =  helper.SuccessMsg();
        console.log(reply);//still it prints /*FAILURE*/
        
    })
});
question from:https://stackoverflow.com/questions/65599240/how-to-set-variable-and-access-from-cypress-framework

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's some async stuff going on here, since cy.exec spawns a child process.

Normally you would await the async call, but Cypress commands only return chainers (they don't really follow the promise pattern), so you will need to add a Promise into the mix and await it.

Helper

module.exports = function() {

  this.returnStatus = "FAILURE";

  this.SuccessMsg = function() {      
    return new Cypress.Promise(resolve => {
      cy.exec('echo hello',  { log: true, failOnNonZeroExit: false }).then((output) => {
        this.returnValue = "SUCCESS";
        resolve(this.returnValue)
      });
    })
  }
}

Test

let Status = require('../support/returnStatus');
let helper = new Status();

describe("Check return value", function(){

  it("should check latest value", async function(){  // NOTE async test
      let reply =  await helper.SuccessMsg();
      console.log('reply', reply);  // now it prints /*SUCCESS*/
  })
});

If you turned your helper function into a custom command, likely the test will not need to be made async since Cypress automatically waits for promises to resolve.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...