【问题标题】:how to integration test nodeJS mongo如何集成测试nodeJS mongo
【发布时间】:2014-10-17 17:50:37
【问题描述】:
作为设置持续集成周期的一部分,我们正在为我们的平均应用程序定义单元和集成测试的标准模板。
一项基本测试是验证 mongo 集合中的一些设置(名称设置)
我们正在使用 Mocha、Should、Require 和 super test
我已经定义了以下测试
var request = require('supertest');
描述('配置',function(){
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: Cannot call method 'findOne' of undefined'
谁能指出我正确的方向如何在 mongo 对象上使用集成测试(例如检查集合计数
【问题讨论】:
标签:
node.js
unit-testing
mongoose
【解决方案1】:
考虑到设置是一个猫鼬模型,你会在模型文件的末尾有这个
setting.js
...
module.exports = mongoose.model('Setting', settingSchema)
我想如果你在你的测试文件中需要这个模型
test.js
var Setting = require('./setting')
然后您可以在实际测试用例中调用Setting.findOne 而不是mongoose.Setting.findOne,它应该可以正常工作。此外,在执行此操作之前,您应该确保已成功连接到您的测试数据库。在 before 钩子中清理测试的集合是一个好习惯
before(function(done) {
// Connect to database here
Setting.remove({}, function(err) {
if (err)
throw err
else
done()
})
})
并做同样的事情afterEach 测试用例。
我看不到您在 sn-p 中的何处以及如何使用 supertest,但我相信它是正确的工具。同样,在您的 before 钩子中,您可以首先调用 request = request(require('./app')) app.js 导出您的快速应用程序。此外,您可以将连接到数据库的代码移动到您的 app.js 中,这感觉更加独立于环境。
【解决方案2】:
在编写单元和集成测试之前,您应该安装所需的库
-
全局安装 mocha 框架
sudo npm install -g mocha
-
安装chai断言库和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);
}};