【发布时间】:2021-03-11 18:26:22
【问题描述】:
我正在尝试实现 mocha 和 chai 简单测试,但响应中有错误,我无法弄清楚为什么它不能通过。 Stackoverflow 上有一些与我类似的问题,我尝试了那里给出的解决方案和建议,但没有结果,所以我决定创建另一个问题。
我想做的事:
我想测试对/api/flashCards 端点的请求,它应该返回两个对象:
[
{
"_id": "1",
"front": "hello",
"back": "czesc"
},
{
"_id": "2",
"front": "apple",
"back": "jablko"
}
]
这些对象被添加为固定装置(使用node-mongodb-fixtures),因为我不想在真正的数据库上测试它。我正在使用chai-http 在测试文件中提出请求。下面你可以看到完整的测试文件代码。
const DB_URI = "mongodb://localhost:27017/flashCard";
const Fixtures = require("node-mongodb-fixtures");
const fixtures = new Fixtures();
const chai = require("chai");
const expect = require("chai").expect;
const chaiHttp = require("chai-http");
const app = require("../src/app");
chai.use(chaiHttp);
const endpoint = "http://localhost:4000/api/flashCard";
describe("FlashCards", () => {
before((done) => {
fixtures
.connect(DB_URI)
.then((res) => {
res.unload();
res.load();
done();
})
.catch((error) => done(error));
});
after((done) => {
fixtures
.unload()
.then(() => {
fixtures.disconnect();
done();
})
.catch(done);
});
it("should allow me to get flashcard if I dont have auth token", (done) => {
console.log("asdasasdasd");
chai
.request(app)
.get(endpoint)
.then((res) => {
const body = res.body;
expect(res.status).to.equal(200);
expect(body).to.contain.property("front", "hello");
expect(body).to.contain.property("back", "czesc");
done();
})
.catch((err) => done(err));
});
});
运行测试命令后控制台的响应是:
$ npm run test
> flashCards@1.0.0 test C:\Users\pstan\Desktop\flashCards
> mocha --require @babel/register --recursive --exit
[info ] Using fixtures directory: fixtures
[info ] No filtering in use
Listening on port 4000
FlashCards
(node:16760) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
[info ] Using database flashCard
asdasasdasd
[start] load flashcards
[done ] unload flashcards
[done ] *unload all
[done ] load flashcards
[done ] *load all
[done ] *script all
1) should allow me to get flashcard if I dont have auth token
[done ] unload flashcards
[done ] *unload all
0 passing (2s)
1 failing
1) FlashCards
should allow me to get flashcard if I dont have auth token:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\pstan\Desktop\flashCards\test\flashcards.js)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
当我在测试运行命令中添加更多timeout: 10000时,错误信息改为:
1) FlashCards
should allow me to get flashcard if I dont have auth token:
Error: connect ECONNREFUSED 127.0.0.1:80
我不明白我在这里做错了什么。我还在学习 mocha 并在后端进行测试,所以我认为问题可能是我对它的工作原理缺乏了解,但我希望你能帮助我。
在数据库中创建了固定装置(在mongo compass 中检查),当我在postman 中点击端点时,我得到了正确的响应。
【问题讨论】:
标签: node.js testing mongoose mocha.js chai