【问题标题】:Cypress stubbing seems to yield response from actual server赛普拉斯存根似乎会产生来自实际服务器的响应
【发布时间】:2018-04-18 20:57:59
【问题描述】:

在现有项目中试用赛普拉斯时,我遇到了路由响应的存根问题。此文档文章中解释了该概念: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 中:

但响应是 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() 发送的。实际的服务器在localhost:3000 上运行,我在我的cypress.json 文件中将其指定为baseUrl

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

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

【问题讨论】:

    标签: javascript testing stubbing cypress


    【解决方案1】:

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

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

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

    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');
      });
    
    });
    

    【讨论】:

    • 谢谢!这就解释了。
    • 顺便说一下,在阅读文档时,这些信息对我来说并不明显。我尝试将信息添加到 cy.request 和 cy.route 的文档中。看到这个 PR:github.com/cypress-io/cypress-documentation/pull/225
    • @jennifer 如果内容类型是 text/html,响应的结构应该是什么?如果我创建一个简单的存根路由,例如cy.route("GET", /thankyou_page, response.body),它会从服务器返回实际的 html,而不是我通过的那个。
    猜你喜欢
    • 2021-08-08
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2021-08-08
    相关资源
    最近更新 更多