2

I am trying to set some variables based on the results of a cy.exec() command for use later in the script. For example:

cy.exec('some command').then((result) => { let json = JSON.parse(result.stdout) this.foo = json.foo }) 

How can I wait for this.foo to be defined before proceeding with the rest of the script? I tried:

cy.exec('some command').as('results') cy.wait('@results') 

However this.results is undefined after the cy.wait() command.

1 Answer 1

4

You don't need aliases. Your code is correct, but you can't use this inside of a () => {}. You should use a function declaration to make use of this.

Try this instead:

cy.exec('some command').then(function(result) { let json = JSON.parse(result.stdout) this.foo = json.foo }) 

Note that Cypress is asynchronous. What this means is that if you do something like this:

cy.exec('some command').then(function(result) { let json = JSON.parse(result.stdout) this.foo = json.foo }) expect(this.foo).to.eq(expectedStdout) 

...your test will always fail. this.foo = json.foo will be executed after the expect(this.foo)... is evaluated.

If you want to use this.foo in this way, just use the Promise returned by cy.exec():

cy.exec('some command').then(result => { return JSON.parse(result.stdout) }) .then(json => { // write the rest of your test here cy.get('blah').contains(json.something) }) 
Sign up to request clarification or add additional context in comments.

4 Comments

How can I reference the value of json.something in other tests outside of the "then" block?
You can't, it's asynchronous
You could return the Promise from the beforeEach, then it would run before your tests do
Ah, using a hook is the piece I was missing. The combination of putting my setup code in before() and not trying to use this in an arrow function was the solution for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.