我通过API获取真实数据,然后像这样判断响应是成功还是失败.

{ message: "fail" }

如果消息是失败,我想强制测试失败,我还想判断状态是否正常.即使使用抛出新错误,测试仍然是成功的.

enter image description here

我的代码是这样的

describe('fetch Data', () => {
  beforeEach(() => {
    cy.visit('http://localhost:3000');
  });

  it('Fetch Data', () => {
    fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843').then((response) => {
      if (!response.ok) {
        throw new Error('Something went wrong!');
      } else {
        return response.json();
      }
    }).then((res) => {
      expect(res.message).to.contain('success');
      cy.log('result => ', res);
    }).catch((err) => {
      throw new Error(err);
    });
  });
});

推荐答案

基本上,fetch()以及后续的.then().catch()没有在Cypress队列上运行,因此它不知道测试何时完成.

您可以将fetch()转换为cy.request()来绕过这一点.

但要继续获取,请在Catch块中使用Mocha的done()方法来表示测试结束

it('Fetch Data', (done) => {
  fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
  .then((response) => {
    if (!response.ok) {
      throw new Error('Something went wrong!');
    } else {
      return response.json();
    }
  }).then((res) => {
    expect(res.message).to.contain('success');
    cy.log('result => ', res);
    done()
  })
  .catch((err) => {
    throw new Error(err);
    done()
  })
})

删除CATCH子句也会使测试失败.

it('Fetch Data', () => {
  fetch('https://mocki.io/v1/82b25ba1-615a-4ff6-8c5d-c9f464f8c843')
  .then((response) => {
    if (!response.ok) {
      throw new Error('Something went wrong!');
    } else {
      return response.json();
    }
  }).then((res) => {
    expect(res.message).to.contain('success');
    cy.log('result => ', res);
  })
})

Javascript相关问答推荐

有没有方法在Angular中的bowser选项卡之间移动HTML?

使用ReactJS对Ant Design表中的空值进行排序

响应式JS DataTable中的Bootstrap 5弹出程序无法正常工作

Angular:ng-contract未显示

Express.js:使用Passport.js实现基于角色的身份验证时出现太多重定向问题

将数据从strapi提取到next.js,但响应延迟API URL

我无法在NightWatch.js测试中获取完整的Chrome浏览器控制台日志(log)

Cypress -使用commands.js将数据测试id串在一起失败,但在将它们串在一起时不使用命令有效

被CSS优先级所迷惑

docx.js:如何在客户端使用文档修补程序

在JavaScript中声明自定义内置元素不起作用

无法检测卡片重叠状态的问题

XSLT处理器未运行

JS—删除对象数组中对象的子对象

在执行异步导入之前判断模块是否已导入()

在运行时使用Next JS App Router在服务器组件中运行自定义函数

IF语句的计算结果与实际情况相反

在forEach循环中获取目标而不是父对象的属性

在VS代码上一次设置多个变量格式

如何在Java脚本中对数据进行签名,并在PHP中验证签名?