I am trying to compare two JSON files in Cypress.
To see if this works I simply made a copy of data.json and renamed its copy to data2.json.
var comparejson = cy.readFile('data2.json')
cy
.readFile('data.json')
.then(json => JSON.stringify(json)).should('eq', JSON.parse(comparejson))
This is the error I get:
SyntaxError: Unexpected token o in JSON at position 1
Ah, the dreaded token o. It's reading the 'o' from [object Object], which is the toString representation of a Plain Ol' JavaScript Object.
You can test this for yourself, by the way, by entering a JavaScript REPL and:
08:54 $ node
Welcome to Node.js v13.0.1.
Type ".help" for more information.
> JSON.parse({}.toString())
Thrown:
SyntaxError: Unexpected token o in JSON at position 1
> ({}).toString()
'[object Object]'
So in the future, any time you see that error you know you've skipped a step in stringifying somewhere!
The trick here is that readFile returns an object (not a string, JSON files are parsed by Cypress into JavaScript) but you're calling JSON.parse on the object.
Try this:
cy
.readFile('data2.json')
.then(data2 => cy.readFile('data.json').should('deep.equal', data2))
Note use of deep.equal here, since we're comparing objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With