首页 > 解决方案 > Cypress-compare file contents with an array always return false

问题描述

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

标签: javascriptarrayscypress

解决方案


I made a test locally and:

  • rename your Latest.txt file into Latest.json so we can leverage a Cypress feature that automatically parses the file
  • the file content must be
[
 "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


推荐阅读