我正在try 验证来自OpenweatherAPI的API响应.

我正在执行以下步骤

  1. 创建带有POST呼叫的气象站
  2. 从步骤1获取外部ID
  3. 将外部ID与GET RESPONSE匹配并通过测试.如果在GET响应中未找到外部ID,则测试失败
it.only('first POST and array iteration', () => {
        cy.request({
            method: 'POST',
            url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea',
            headers: {
                'Accept': 'application/json'
            },
            body: {
                "external_id": "testweatherapi12",
                "name": "weather_api12",
                "latitude": 35.55,
                "longitude": 89.45,
                "altitude": 56.4
            }
        }).then((res) => {
            cy.log('response is ' + JSON.stringify(res));
            let idIs = res.body.ID;
            cy.log('ID****** is ' + idIs);
            expect(res.status).to.eq(201)

        }).then((res) => {
            cy.request({
                method: 'GET',
                url: 'https://api.openweathermap.org/data/3.0/stations?appid=7fe67bf08c80ded756e598d6f8fedaea',
                headers: {
                    'Accept': 'application/json'
                }
            }).then((res) => {
                for (var x = 0; x < res.body.length; x++) {
                    expect(res.body[x].id).to.eq(res.body.ID); //This is failing
                }
            })

        })
    })

推荐答案

我会改变三件事:

  • 在第一个.then(res => )块中,返回res,或者更准确地说,返回return cy.wrap(res),因为在第一个.then(res => )块中有一个cy.log(),如果不包装它,Cypress会抱怨105.

  • 在第二个.then(res => )块中也使用不同的变量名.目前,expect()只使用了第二个res,而忽略了第一个res

  • 使用console.log('response is ', res)进行调试,您会更享受它.

  • 如果您将日志(log)放入每个.then(res => )个块中,您将看到第二个块是null,因为没有return值.

cy.request({
  ...
})
  .then(res => {
    console.log('response is ', res)
    ...
    return cy.wrap(res)            // <- must pass on the res variable
  })
  .then(res => {
    console.log('response is ', res)
    cy.request({
      ...
    }).then(res2 => {                             // <- must use a different variable
      for (var x = 0; x < res.body.length; x++) {
        expect(res2.body[0].id).to.eq(res.body.ID)   // This is now passing ✅
      }
    })
  })

您在第二个响应中有很多不同的ID,所以您可能想要这样,这会给出一个结果:

const matching = res2.body.filter(item => item.id === res.body.ID)

在任何情况下,您都可以在控制台中查看这两个响应,并决定需要比较哪些响应.

Typescript相关问答推荐

如何在Jest中嘲笑location.back()方法调用进行Angular 组件测试?

动态判断TypScript对象是否具有不带自定义类型保护的键

JS Redux Devtools扩展不工作

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

在类型脚本中的泛型类上扩展的可选参数

如何调整对象 struct 复杂的脚本函数的泛型类型?

为什么有条件渲染会导致material 自动完成中出现奇怪的动画?

带下拉菜单的Angular 响应式选项卡

Angular:ngx-echart 5.2.2与Angular 9集成错误:NG 8002:无法绑定到选项,因为它不是div的已知属性'

在React中定义props 的不同方式.FunctionalComponent

基于泛型的条件接口键

如何将类似数组的对象(字符串::匹配结果)转换为类型脚本中的数组?

如何连接属性名称和值?

为什么特定的字符串不符合包括该字符串的枚举?

是否将Angular *ngFor和*ngIf迁移到新的v17语法?

如何在Next.js和Tailwind.css中更改悬停时的字体 colored颜色

基于属性值的条件类型

我可以使用JsDocs来澄清Typescript实用程序类型吗?

TypeScript:方法获胜';t接受较窄类型作为参数

如何使用 AWS CDK 扩展默认 ALB 控制器策略?