Reputation: 604
Within Cypress I am opening a JSON file and I want to use values within that file to check in a test.
I open the file using cy.readfile()
this is my code to read:
let expectedTimeOfTest = "";
cy.readFile(filePath + fileName).then((json) => {
expect(json).to.be.an('object')
expectedTimeOfTest = JSON.stringify(json.SEQUENCE.timeoftest);
cy.log(">>" + expectedTimeOfTest);
});
When I run the test, I can see in the runner that the text appears in the log as I expect.
Now later on I try to assert, I use:
cy.get('.testClass').eq(1).should('have.text', expectedTimeOfTest);
However, the test fails with the error "expected .testClass to be '' but got ''
I cannot see what I have done wrong? Any ideas?
Upvotes: 2
Views: 2272
Reputation: 431
Depending on where you're executing your assertion, and due to Cypress' asynchronous nature, you may be trying to assert before expectedTimeOfTest
is actually being assigned a value. You have one of two options:
cy.wrap(JSON.stringify(json.SEQUENCE.timeoftest)).as("expectedTimeOfTest");
which you can then access by its alias as either this.expectedTimeOfTest
or cy.get("@expectedTimeOfTest")
later in your test.If you go this route, do not use the arrow function for your then
method, as aliases won't work with them. Instead use .then(function(){ //your code here})
// Example of using function() vs arrow function.
cy.readFile(filePath + fileName).then(function(json){
expect(json).to.be.an('object')
cy.wrap(JSON.stringify(json.SEQUENCE.timeoftest)).as("expectedTimeOfTest");
});
.then()
method.Upvotes: 2
Reputation: 8362
If you have cy.get('.testClass').eq(1).should('have.text', expectedTimeOfTest);
outside of the .then()
of cy.readFile()
, then it's better to put it inside because cy.readFile()
is asynchronous:
cy.readFile(filePath + fileName).then((json) => {
expect(json).to.be.an('object')
expectedTimeOfTest = JSON.stringify(json.SEQUENCE.timeoftest);
cy.get('.testClass').eq(1).should('have.text', expectedTimeOfTest);
});
You can also use aliases:
cy.readFile(filePath + fileName).as('myFile');
cy.get('@myFile')
Upvotes: 0