我在Cypress 6中存在数据存根问题。我试图实现从服务器到自定义数据的真实数据交换。我阅读了文档,得出的结论是
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
server.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}`);
});
index.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服务器和客户端端口?
我设置了服务器,发现它可以正常工作。
我唯一更改的是在服务器响应中添加了一个无存储头(停止浏览器看到状态码“ 304”)。
没有它,赛普拉斯测试的每一秒刷新都cy.intercept()
不会触发。通过在其中添加完整的路由匹配器cy.intercept()
而不是仅添加URL,实际上可以在测试中解决此问题。
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store')
next()
})
app.get("/", (req, res) => {...
我还将应用程序中的脚本修改为console.log in .then()
,否则您只会得到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')
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句