Как я могу использовать кипарис, чтобы сделать JSON звонок? - PullRequest
0 голосов
/ 18 февраля 2020

День первый с Cypress.
Попытка сделать JSON звонок и проверить результат, но все попытки дают мне неопределенное значение.

describe('Test Number 000001 !!!', function() {
  it('starts off OK', function() {
    expect(true).to.equal(true)
  })  
  it('can call the example api', function() {
    cy.request('https://jsonplaceholder.typicode.com/todos/1')
  })  
  it('can call the example api and store the result', function() {
    result = cy.request('http://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json()) // I tried with and without then
    expect(result).to.equal(1) // will fail but once i get real response I will adjust
  })  
})

enter image description here

enter image description here

Обновление: ниже проходит ... но на самом деле ничего не проверяется (все используемые значения будут проходить)

    cy.request('http://jsonplaceholder.typicode.com/todos/1').
    then((response) => {
      response = JSON.stringify(response)
      var jsonData = JSON.parse(response)
      for (var i = 0; i < jsonData.length; i++) {
        expect(jsonData[i]['xuserId']).to.equal(1)
      }
    })

Ответы [ 2 ]

2 голосов
/ 19 февраля 2020

Я использовал тот же тестовый API ранее и получил результаты, как показано ниже; Пожалуйста, посмотрите. Я использовал response.body., чтобы получить json значения

it('Sample Api testing', function () {
        cy.request({
            method: 'get',
            url: 'https://jsonplaceholder.typicode.com/todos/1',
            headers: {
                'accept': 'application/json'
            }
        }).then((response) => {
            expect(response.status).to.eq(200);
            expect(response.body.userId).to.eq(1);
            expect(response.body.id).to.eq(1);
            expect(response.body.title).to.eq('delectus aut autem');
        })
    })

enter image description here

0 голосов
/ 18 февраля 2020

Необходимо преобразовать объект ответа в строку json, используя функцию stringify внутри обещания.

.then((response) => {
    response = JSON.stringify(response)
    var jsonData = JSON.parse(response)
    for (var i = 0; i < jsonData.length; i++) {
     expect(jsonData[i]['userId']).eq(1)
       }

edit

expect(jsonData[i]['userId']).to.equal(1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...