我有以下问题:
我正在使用 Cypress 进行自动化测试。 我创建了一个本地服务器,一个端点,我总是需要在测试之前启动并在测试之后始终关闭。
我尝试了一种方法,但出现以下错误:
Error: Webpack Compilation Error
./node_modules/mysql2/node_modules/lru-cache/dist/mjs/index.js 51:11
Module parse failed: Unexpected character '#' (51:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| length;
| private constructor
> static #constructing = false;
| static create(max) {
| const HeapCls = getUintArray(max);
@ ./node_modules/mysql2/lib/parsers/parser_cache.js 3:12-32
@ ./node_modules/mysql2/promise.js
有人可以帮助我吗?
我上传到服务器的文件(index.js):
const express = require("express");
const app = express();
const port = 3000;
const programmingLanguagesRouter = require("./routes/programmingLanguages");
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
app.get("/", (req, res) => {
res.json({ message: "ok" });
});
app.use("/programming-languages", programmingLanguagesRouter);
/* Error handler middleware */
app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
console.error(err.message, err.stack);
res.status(statusCode).json({ message: err.message });
return;
});
function test() {
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
}
module.exports = test();
我的测试文件,我需要通过调用index.js文件(test.spec.js)上传到服务器:
const xxxx = require('../../../../../../../../index.js');
describe("Calling the endpoint", async () => {
context("Test", () => {
it("Test", () => {
xxxx.tes()
cy.request({
method: 'GET',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json'
},
url: 'localhost:3000/programming-languages'
}).then((res) => {
expect(res.status).to.equal(200);
});
});
});
});
当我调用命令“node index.js”时,服务器成功启动,我可以访问我的端点。
问题是尝试在我的测试文件中上传服务器并在之后立即关闭。
你能帮我吗?
提前非常感谢您!
服务器索引中的代码只能在 NodeJs 中运行,但您已尝试将其拉入在浏览器上下文中运行的测试中。
// in test
const xxxx = require('../../../../../../../../index.js');
// but express.js does not work in the browser.
我不知道你发布的错误是否是由此引起的,它实际上看起来像其他东西。
但是首先要做的是纠正服务器启动。
我建议您仔细阅读此示例并使其适应您的服务器索引代码。
最重要的是脚本,用于在启动 Cypress 之前启动服务器。
这大致就是您所需要的:
{
...
"scripts": {
"start": "/server/index.js",
"cy:run": "cypress run",
"test": "start-server-and-test start http://localhost:3030 cy:open"
}
}