javascript - 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
解决方案
I made a test locally and:
- rename your
Latest.txt
file intoLatest.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
推荐阅读
- c++ - 运行时错误 - 地址释放后堆使用
- php - 如何将 Woocommerce 多参与者自定义元数据包含到新订单电子邮件中
- excel - 减少 M 查询响应时间
- android - AdMob 真实广告不显示
- python - 安装 Pygal 的问题
- scala - 如何将枚举类型传递给函数
- javascript - Jeditable 未正确提交
- postgresql - 使用 shell 脚本(postgresql)中的替换函数将单词替换为“(双引号)
- angular - 如何使用角度将对象添加到包含 Array 的现有动态秋田商店
- node.js - 如何设置从 Node 服务器到 React 前端的音频流?