javascript - 拦截真实数据响应

标签 javascript automated-tests cypress

我在 Cypress 6 中遇到数据 stub 问题。我正在尝试实现从服务器到自定义数据的真实数据交换。我阅读了文档并得出结论

describe("test", () => {
  it("intercept", () => {
    cy.intercept("http://localhost:3000/spoons", (req) => {
      req.reply((res) => {
        let { body } = res;
        body.newProperty = "new";
        console.log(res.body);
        return body;
      });
    });
  });
});

将是解决方案,但是......请求http://localhost:3000/spoons的网络中的主体返回给我
{
  "sizes": [
    "huge",
    "small"
  ],
  "colors": [
    "yello",
    "brown"
  ],
  "build": {
    "back": true,
    "front": true
  }
}
但是在 console.log 中,因为它显示了 res.body 有什么,它会得到一个 空的 console.log 就好像它没有 res.body 一样。
编辑 #1
关于内部“服务器”,我制作了一个带有网站的简单快速服务器,该网站使获取请求在“网络”中轻松实现另一个请求。它只是作为训练 intercept 和其他东西的战场。这个 /spoons 有唯一的端点
服务器.js
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");

const obj = {
  sizes: ["huge", "small"],
  colors: ["yello", "brown"],
  build: {
    back: true,
    front: true,
  },
};

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/index.html"));
});

app.get("/spoons", (req, res) => {
  res.json(obj);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
索引.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    console.log(fetch("http://localhost:3000/spoons"));
  </script>
</html>

最佳答案

它用于拦截外部网络请求,

/// <reference types="@cypress/fiddle" />

const test = {
  html: `
    <script>
      fetch('https://jsonplaceholder.typicode.com/todos/1')
    </script>
  `,
  test: `
  cy.intercept('https://jsonplaceholder.typicode.com/todos/1', req => {
    req.reply((res) => {
      let { body } = res;
      body.newProperty = "new";
      console.log(res.body);
      return body;
    });
  })
  `
}
it('test', () => {
  cy.runExample(test)
})
这日志
{
  completed: false,
  id: 1,
  newProperty: "new",           // added by intercept
  title: "delectus aut autem",
  userId: 1
}
你能更详细地解释api服务器和客户端端口吗?

我设置了你的服务器,发现它工作正常。
我唯一改变的是向服务器响应添加一个 no-store header (阻止浏览器看到状态代码“304”)。
没有它, Cypress 测试的每秒刷新一次 cy.intercept() 不会触发。通过向 cy.intercept() 中添加一个完整的路由匹配器而不仅仅是 url,这实际上可以在测试中解决。
app.use((req, res, next) => {
  res.set('Cache-Control', 'no-store')
  next()
})

app.get("/", (req, res) => {...
我还将应用程序中的脚本修改为 .then() 中的 console.log ,否则你只会得到 promise 对象。
<script>
  fetch('http://localhost:3000/spoons')
    .then(res => res.json())
    .then(res => console.log('app', res))
</script>
这是我使用的规范。
it('test', () => {
  cy.intercept('http://localhost:3000/spoons', req => {
    req.reply((res) => {
      let { body } = res;
      body.newProperty = "new";
      console.log('intercept', res.body);
      return body;
    });
  })
  cy.visit('../app/intercept-mod-response-local-server-2.html')
})

关于javascript - 拦截真实数据响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65155934/

相关文章:

javascript - 用户界面路由器 : Best way to initialize variables when state is accesed

javascript - Chrome 中的 Firebase Cloud Messaging Service Worker 重定向

scope - 绑定(bind)中的多个范围值 (Specflow)

java - Action 移动不适用于 : Firefox versions:48 and Selenium: 3. 0.1

javascript - 使用 'contains' 还是 'get' 来查找元素更好?

javascript - 在 Laravel Mix 中删除临时文件

javascript - Typescript/Javascript 中的 Swift 闭包

unit-testing - WatiN 测试记录器 : How to get the compiled code in C# from the steps the recorder records

cypress - 在受 Windows 身份验证保护的 Intranet 应用程序上编写 Cypress 测试

integration-testing - Cypress click() 失败,因为该元素在迭代中与 DOM 分离