Cypress.io-声明没有XHR请求到URL吗? [英] Cypress.io - Assert no XHR requests to URL?

查看:188
本文介绍了Cypress.io-声明没有XHR请求到URL吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用cypress.io进行测试时,有没有一个好的方法来断言没有对给定URL进行XHR请求?

When testing with cypress.io, is there a good way to assert that no XHR requests were made to a given URL?

我想断言一个新的单击保存按钮时添加foo,但单击取消按钮时不添加。

I want to assert that a new foo is added when the "Save" button is clicked, but not when the "Cancel" button is clicked.

类似这样的事情:

cy.route('POST', '/foos').as('postFoo');
cy.get('.cancel-button').click();
cy.route('@postFoo').should('not.have.been.called'); // (magic imaginary syntax!)

我尝试使用onRequest设置cy.route回调执行assert.fail,但在调用URL时不会失败。

I've tried setting up the cy.route with an onRequest callback that does an assert.fail, but that's not failing the test when the the URL is called.

目前,我捕获了(故意)无请求发生这样的错误:

For now, I'm catching my (intentional) "no request occurred" errors like this:

cy.on('fail', (err, runnable) => {
  expect(err.message).to.include('No request ever occurred.');
  return false;
});  

cy.wait('@postFoo', { timeout: 0 }).then(xhr => {
  throw new Error('Unexpected API call.');
});

...这似乎有效,但肯定不会感觉很柏油 。

...which seems to be working, but it certainly doesn't feel very "cypress-y".

推荐答案

您可以重新命名路线并更改其 onRequest 行为以引发; 但是通常,更糟糕的是断言事情没有发生,因为它们是不确定的。 继续操作之前,您应该等待错误多长时间?

You can re-alias your route and change its onRequest behavior to throw; however it's generally worse to assert that things didn't happen because they are non-deterministic. How long should you wait around for the error before moving on? :

cy.route({
  method: 'POST',
  url: '/foos',
  onRequest: () => {
    throw new Error('Whoops')
  }
})
cy.get('.cancel-button').click();
cy.wait(1000)  // give it one second to throw, then move on

具有这样的断言只会给测试增加不必要的时间。此类测试称为《赛普拉斯文档》中提到的条件测试

Having assertions like this will only add unnecessary time to your tests. This type of test is know as Conditional Testing as mentioned in the Cypress Docs

这篇关于Cypress.io-声明没有XHR请求到URL吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆