Reputation: 455
I am new to java script and cypress. I am reading contents from a file using cy.readFile command and compare it with another array(which contains run time values). My intention is to compare values in baseline file and run time values.I tried to use below assertion but it failing.
cy.readFile('Latest.txt').should('eq',tableValues1);
this assertion fails-console Output shows like below- as you can see the contents in expected and actual are same -something with the format -can any one give me a hint.
Actual: [
"Gender",
"Age group ",
"Source Total ",
"21 to 30 ",
"30 to 35 ",
"36 to 40 ",
"41 to 45 ",
"46 to 50 ",
"51 to 55 ",
"56 to 60 ",
"61 to 65 ",
"Over 66 ",
"123",
"%",
"%",
"%",
"%",
"%",
"%",
"%",
"%",
"%"
]
cypress_runner.js:163813
Expected: (22) ["Gender", "Age group ", "Source Total ", "21 to 30 ", "30 to 35 ", "36 to 40 ", "41 to 45 ", "46 to 50 ", "51 to 55 ", "56 to 60 ", "61 to 65 ", "Over 66 ", "123", "%", "%", "%", "%", "%", "%", "%", "%", "%"]
I have also tried to compare like
tableValues1==cy.readFile('Latest.txt');
this also return false
Upvotes: 2
Views: 5649
Reputation: 3709
I made a test locally and:
Latest.txt
file into Latest.json
so we can leverage a Cypress feature that automatically parses the file[
"Gender",
"Age group ",
"Source Total ",
"21 to 30 ",
"30 to 35 ",
"36 to 40 ",
"41 to 45 ",
"46 to 50 ",
"51 to 55 ",
"56 to 60 ",
"61 to 65 ",
"Over 66 ",
"123",
"%",
"%",
"%",
"%",
"%",
"%",
"%",
"%",
"%"
]
that is a valid JSON file (you can check it pasting it on a validator)
Now that we're sure that there aren't any decoding issue etc. (because Cypress automatically converts the JSON file into a JavaScript object) we can compare them.
Anyway: Cypress will still tell you that they aren't equal but it's not a big issue, other testing libraries (Jest etc.) sometimes fail making comparisons like yours. All you have to do is to convert both the objects to a baseline JSON string and compare them.
Try that
cy.readFile('example.json').then(json => JSON.stringify(json)).should('eq',JSON.stringify(tableValues1));
where
cy.readFile('example.json') // reads the file as expected
.then(json => JSON.stringify(json)) // once read, it converts the file into a JSON string
.should('eq', JSON.stringify(tableValues1)); // and compare it to the stringified version of your array
It works for me locally and you can find it working on my GitHub repository, let me know if you need something more 😊
Upvotes: 3
Reputation: 18043
1) eq
checks object references. You want deep.eq
to assert contents of an object/array are equal.
2) like NoriSte mentioned below, you need to parse the .txt
into a javascript
object:
cy.readFile('example.txt')
.then(text => JSON.parse(text))
.should('deep.eq', tableValues1)
or let cypress do it for you (rename the file to .json
):
cy.readFile('example.json')
.should('deep.eq', tableValues1)
Upvotes: 3