Node.js 如何集成测试nodejsmongo
作为建立持续集成周期的一部分,我们正在为我们的应用程序定义单元和集成测试的标准模板。 一个基本测试是验证mongo集合名称设置中的一些设置 我们正在使用摩卡咖啡,应该,需要和超级测试 我定义了以下测试 var请求=要求“超级测试”; 描述“配置”和“功能”{Node.js 如何集成测试nodejsmongo,node.js,unit-testing,mongoose,Node.js,Unit Testing,Mongoose,作为建立持续集成周期的一部分,我们正在为我们的应用程序定义单元和集成测试的标准模板。 一个基本测试是验证mongo集合名称设置中的一些设置 我们正在使用摩卡咖啡,应该,需要和超级测试 我定义了以下测试 var请求=要求“超级测试”; 描述“配置”和“功能”{ before(function(done) { // In our tests we use the test db mongoose.connect(config.db); done(); }); describe
before(function(done) {
// In our tests we use the test db
mongoose.connect(config.db);
done();
});
describe('required configuration ',function(){
it('should return Settings Object',function(done){
mongoose.Setting.findOne({key:'ABC'}, function(foundSetting){
foundSetting.value.should.equal('XYZ');
done();
});
})
});
}
其中始终存在“TypeError:无法调用未定义的”的方法“findOne”错误
有人能告诉我如何在mongo对象上使用集成测试的正确方向吗?例如,检查集合计数考虑到设置是一个mongoose模型,您可以在模型文件的末尾使用此设置
setting.js
...
module.exports = mongoose.model('Setting', settingSchema)
我想如果你在测试文件中需要这个模型
test.js
var Setting = require('./setting')
然后您可以在实际测试用例中调用Setting.findOne而不是mongoose.Setting.findOne,它应该可以正常工作。在执行此操作之前,还应确保已成功连接到测试数据库。在挂钩前清洁测试收集物是一种良好的做法
before(function(done) {
// Connect to database here
Setting.remove({}, function(err) {
if (err)
throw err
else
done()
})
})
并在每个测试用例之后执行相同的操作
我不知道您在代码片段中使用supertest的位置和方式,但我相信它是正确的工具。同样,在before钩子中,您可以首先调用request=requestrequire'./app',其中app.js导出您的express应用程序。此外,您可以将连接到数据库的代码移动到您的app.js,这让您感觉更独立于环境。在编写单元和集成测试之前,您应该安装所需的库 全球安装mocha框架
sudo npm install -g mocha
安装断言库和HTTP插件
npm install chai
npm install chai-http
将mocha命令添加到package.json文件
"scripts": {
"test": "mocha",
"start": "nodemon app.js"
}
在下面的代码中可以看到mocha框架和chai断言库的用法
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.should();
chai.use(chaiHttp);
describe("Integration Test Case 1",() => {
it("Sign Up-In", () => {
// Sign Up
chai.request("localhost:5000/api/users")
.post("/signup")
.send(createdUser)
.end(async (error, response) => {
await response.should.have.status(201);
// Sign In
chai.request("localhost:5000/api/users")
.get("/signin")
.send(userCredential)
.end(async (error, response) => {
await response.should.have.status(202);
}};