stdout
stdout

Reputation: 1779

Cypress.io: Waiting for results of exec command

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.

Upvotes: 2

Views: 4549

Answers (1)

Zach Bloomquist
Zach Bloomquist

Reputation: 5871

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)
})

Upvotes: 4

Related Questions