Sinon / Node / Express / Mongo - 尝试模拟Mongo DB.collection函数时出现TypeError

时间:2016-09-09 20:16:48

标签: node.js mongodb express mocha sinon

我正在尝试为Express / Mongo应用程序编写单元测试,并且我正在尝试使用Sinon来模拟Mongo库,以便我可以在不需要数据库的情况下测试行为。我正在使用co模块来使用Mongo库使用promises。

下面列出的测试会产生以下错误:

[TypeError: db.collection is not a function]
TypeError: db.collection is not a function
    at /myApp/services/v1/project.js:76:20
    at next (native)
    at onFulfilled (/myApp/node_modules/co/index.js:65:19)
project.js中的

行76对应于此行“var col = db.collection('project');”。

我使用Db.prototype模仿了Db对象,如其他地方所建议的那样。

testProject.js

describe('Project Services Tests', function() {

  it('Test Create Project', function(done) {
    var response = buildResponse();
    var request  = HttpMocks.createRequest({
      params: {'name': UNITTESTPROJECT},
      body: {
        name: UNITTESTPROJECT,
        program: "Basic Test Data"}
    });
    var MongoMock = Sinon.mock(MongoClient);
    var DBMock = Sinon.mock(MongoClient.Db.prototype);
    var CollectionMock = Sinon.mock(MongoClient.Collection.prototype);
    var countResult = 1;
    var aResult = {result: {insertedCount: 1}};
    MongoMock.expects('connect').resolves(DBMock);
    DBMock.expects('collection').returns(CollectionMock);
    CollectionMock.expects('count').resolves(countResult);
    CollectionMock.expects('insertOne').resolves(aResult);

    response.on('end', function() {
      should(response.statusCode).equal(HttpStatus.CREATED);
      done();
    });

    project.createProjectByName(request, response);
  });

project.js

co(function*() {
  var db = yield MongoClient.connect(dbUrl);
  var col = db.collection('project');
  var count = yield col.count({name: projectName});
  if (count > 0) {
    db.close();
    res.status(HttpStatus.FORBIDDEN);
    res.send('Project ' + projectName + ' already exists.  Duplicates not permitted');
  }
  var result = yield col.insertOne(project);
  db.close();

  if (result.insertedCount > 0) {
    res.status(HttpStatus.CREATED);
    res.send(req.protocol + '//' + req.hostname + req.originalUrl);
  } else {
    res.status(HttpStatus.INTERNAL_SERVER_ERROR);
    res.send('Project ' + projectName + ' unable to create.');
  }
}).catch(function(err) {
  res.status(HttpStatus.INTERNAL_SERVER_ERROR);
  res.send('Unable to create project' + req.params.name);
});

的package.json

"devDependencies": {
  "mocha": "^3.0.2",
  "node-mocks-http": "^1.5.2",
  "should": "^9.0.2",
  "sinon": "^1.17.5",
  "sinon-as-promised": "^4.0.2"
},
"dependencies": {
  "body-parser": "^1.15.1",
  "co": "^4.6.0",
  "config": "^1.21.0",
  "express": "^4.14.0",
  "http-status-codes": "^1.0.6",
  "log4js": "^0.6.37",
  "method-override": "^2.3.6",
  "mongodb": "^2.2.4",
  "response-time": "^2.3.1",
  "try": "^0.13.3"
}

0 个答案:

没有答案