0

I'm trying to compare that values from UI are matched with json coming from the API response, using JSONPath in a Cypress test.

I want to get iPhone (refer Evaluation Result box) and want to compare it with the UI enter image description here

Here's my test

cy.intercept('https://jsonpath.com/').as('test');
 cy.visit('/');
     
 var jp = require('jsonpath');
 var names = jp.query('@test', '$.phoneNumbers[:1].type');  
 cy.get('@test').should((response) => {
 cy.log(JSON.stringify(test));
      

The error I am getting is

enter image description here

Aying Yong
  • 13
  • 5

3 Answers3

2

The homepage says this is a Node package, so put it in a task

//cypress.config.js

const { defineConfig } = require("cypress");
const jp = require('jsonpath');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
      on('task', {
        jpquery: ({data, query}) => jp.query(data, query),
      })
    },
  },
})

Then the example given on the homepage would be tested this way -

const cities = [
  { name: "London", "population": 8615246 },
  { name: "Berlin", "population": 3517424 },
  { name: "Madrid", "population": 3165235 },
  { name: "Rome",   "population": 2870528 }
];

cy.task('jpquery', { data: cities, query: '$..name' })
  .should('deep.eq', ['London', 'Berlin', 'Madrid', 'Rome'])
Lola Ichingbola
  • 3,035
  • 3
  • 16
2

Change the order of the commands, to start with. Then check what the response actually is before passing it to jp.query().

The object you pass should be, well, an object.

const jp = require('jsonpath');

cy.intercept('https://jsonpath.com/').as('test');
cy.visit('/');
     
cy.wait('@test').then((response) => {
  const phoneNoTypes = jp.query(response, '$.phoneNumbers[:1].type');  
  console.log(phoneNoTypes)
})
Spara
  • 23
  • 5
0

You need to convert the object with JSON.parse.

    cy.get('@test').then((test) => {
      const body = JSON.stringify(test)
      const json = JSON.parse(body)
      const bodyForJp = jp.query(json, "$.phoneNumbers[:1].type");
    })
DmitryArc
  • 4,757
  • 2
  • 37
  • 42
Anderson
  • 31
  • 2