2

I am trying to validate two json file and if the file data is valid then log it as "success", if it is invalid log it as "fails". But my test case tend to show fail all the time even the value present in the file is correct. I checked the values in the file by introducing logs in each function.

I tried the above stuff but i receive "fail" all the time If there could be a solution i would be happy, i am not sure what is wrong output

test.cy.js

cy.get('.dataTable-custom').get('.w-40').eq(0).then((el) => {
                cy.writeFile('request-number.json',
                    {
                        request_number: el.text()
                    })
            })
            cy.readFile('request-number.json').then((request) => {
                expect(request).to.be.an('object')
                cy.log(request)
                cy.readFile('application-details.json').then((json) => {
                    expect(json).to.be.an('object')
                    cy.log(json)
                    if (request === json) {
                        cy.log("success")
                    }
                    else {
                        cy.log("fail")
                    }
                })
            })```
**request-number.json**
`{
  "request_number": "ARS/0099/2023"
}`
  
**application-details.json**
`{
  "request_number": "ARS/0099/2023"
}`


3 Answers3

2

The variables request and json contain references to the objects not the objects themselves.

When you compare them with === you are comparing the references not the contents. In fact you are asking "are these the same object?".

Clearly they are not, since you read them from different sources.

The way to compare the content is with Cypress lodash

_.isEqual(value, other)

Performs a deep comparison between two values to determine if they are equivalent

Note: This method supports comparing arrays, array buffers, booleans, date objects, error objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays

if (Cypress._.isEqual(request, json)) {
  ...
1

why not use just deep equal?

expect(json).to.deep.equal(request)
szogoon
  • 470
  • 3
  • 15
  • 1
    Yes it does - you are misunderstanding the English idiom used - "why not use?" means "you should use", or "there is no reason not to use". – user16695029 Aug 24 '23 at 19:19
0

In Javascript you can't just simply compare two objects using "==" or "===" , you need to convert the object to a stringified version first and then compare.

...
if (JSON.stringify(request) === JSON.stringify(json)) {
    cy.log("success")
  }
  else {
    cy.log("fail")
 }
...

Reference: https://www.educative.io/answers/how-to-compare-two-objects-in-javascript

Ry-ry
  • 210
  • 1
  • 4
  • 15