我正在为cypress中的Web应用程序编写端到端测试,如果应用程序发送任何带有http 500错误响应的请求,我希望cypress无法通过测试。
我在3.1.5版本中使用cypress。我已经尝试过以下内容,但是我收到了一个承诺错误。
cy.server();
cy.route({
url: '**',
onResponse: (xhr) => {
cy.log(xhr);
}
});
我希望找到一个更优雅的解决方案,因为这听起来像一个非常标准的用例。
不确定是否有一些规范的方法,但你可以修补XMLHttpRequest
API并抛出>= 500
状态响应。
如果您的应用使用Fetch API,SendBeacon或其他内容,您可以执行类似的操作。
// put this in support/index.js
Cypress.on('window:before:load', win => {
const origSend = win.XMLHttpRequest.prototype.send;
win.XMLHttpRequest.prototype.send = function () {
// deferring because your app may be using an abstraction (jquery),
// which may set this handler *after* it sets the `send` handler
setTimeout(() => {
const origHandler = this.onreadystatechange;
this.onreadystatechange = function () {
if ( this.readyState === 4 && this.status >= 500 ) {
throw new Error(`Server responded to "${this.url}" with ${this.status}`);
}
if ( origHandler ) {
return origHandler.apply(this, arguments);
}
};
return origSend.apply(this, arguments);
});
};
});
WTBS,这不会非常有用,因为你的app可能想要处理那个500
,而这会阻止它。
更好的解决方案是确保您的app只会抛出未处理的500个响应。