0

在现有项目中尝试赛普拉斯时,我遇到了路由响应的问题。此文档文章中解释了该概念:https ://docs.cypress.io/api/commands/route.html#Without-Stubbing 。

这是一个最小的非工作示例。我正在尝试获取一个空对象作为响应主体:

describe('The new event page', () => {

  it('responds with the stub', () => {
    cy.server();
    cy.route('/dummypath', {});
    cy.request('GET', '/dummypath');
  });

});

存根路由清楚地显示在 GUI 中:

显示在赛普拉斯 GUI 中注册的路由的图片

但响应是 404:

服务器以 404 响应

...具有以下主体:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /dummypath</pre>
</body>

我认为 404 响应是由我的实际服务器而不是 cy.server() 发送的。实际的服务器正在运行,我在 my: -filelocalhost:3000中指定了它。baseUrlcypress.json

有没有人见过类似的东西?我是否忽略了代码中的任何明显错误?

PS: 当我将端口号更改为其他未使用的端口时,错误会变为网络错误(这可能是意料之中的)。

 CypressError: cy.request() failed trying to load:

http://localhost:3002/dummypath

We attempted to make an http request to this URL but the request failed without a response.

We received this error at the network level:

  > Error: connect ECONNREFUSED 127.0.0.1:3002

-----------------------------------------------------------

The request we sent was:

Method: GET
URL: http://localhost:3002/dummypath

-----------------------------------------------------------

Common situations why this would fail:
  - you don't have internet access
  - you forgot to run / boot your web server
  - your web server isn't accessible
  - you have weird network configuration settings on your computer
4

1 回答 1

2

cy.request()向指定的 url 发出实际的 HTTP 请求。在您不想加载实际应用程序的情况下,应使用此命令。例如,您可能想检查服务器上的端点。

cy.route()用于处理在您正在测试的应用程序中发出的 HTTP 请求。

如果您想要对正在测试的应用程序中发出的 HTTP 请求的响应存根,您可能希望使用cy.route()和的组合.wait()。例如,为了确保当我们访问我们的应用程序时,我们的应用程序会发出一个 GET 请求,/dummypath并且该请求的响应是我们的 stubbed {},我们将编写:

describe('The new event page', () => {

  it('responds with the stub', () => {
    cy.server();
    cy.route('/dummypath', {}).as('getDummy');
    cy.visit('http://localhost:3002');         // the url to visit in your app
    cy.wait('@getDummy').its('responseBody')
      .should('be.an', 'object')
      .and('be.empty');
  });

});
于 2017-11-06T17:25:06.240 回答