0

我试图存根 pouchDB 'put' 函数但在调用函数中但它失败了。

我的数据库功能-

var PouchDB = require('pouchDB')
var PendingDB = new PouchDB("")
module.exports.addPendingRequest = function(doc, callback){

  PendingDB.put(doc, function(err, result){
      if(err) {
          console.log("Error in PendingDB: addPendingRequest");
          console.log(err);
          callback(err, null);
      } 
      callback(null, result); 
  });
console.log("after put: inside addPendingRequest");
}

我的测试功能:

var expect = require("chai").expect;
var PendingDB = require("../../lib/administration/PendingDB");
var PouchDB = require('pouchDB');
var sinon = require('sinon');

describe('Testing adding a request', function(){
    it('should save the request with email', function(done){
        var req = {
                _id : "test@email.com",
                first_name: "firstTest",
                last_name: "test",
                id: "test@email.com",
                justif: "Testing Purposes",
        }
        var res = {};
        var next = null;
        console.log("after req, res, next");

        var testOutput = {
        success : "success"
        };

        console.log("after testOutput is set");

        var PendingDBTest = sinon.stub(PouchDB.prototype, 'put', function(err, result){
        console.log("in stub addReq");
    });
        console.log("after sinon.stub");
        expect(function(){
            PendingDB.addPendingRequest(req, function(err, response){
                console.log("response");
                console.log(response);
            });
        }).to.not.throw(Error);

        expect(PendingDBTest.called).to.equal(true);

        PendingDBTest.restore();

        done();

    })
 })

控制台:在 req、res、testOutput 之后设置在 sinon.stub 之后 put 之后:在 addPendingRequest 之后

因此永远不会输入 PendingDB.put 并且我的测试 PendingDBTest.call 返回 false,因此失败。

4

2 回答 2

0

存根在实际对象上,而不是在其原型上。

    var PendingDBTest = sinon.stub(PouchDB, 'put', function(err, result){
          ...
于 2015-09-09T19:51:36.680 回答
0

您可以使用 PouchDB 可用的内存适配器来编写测试,而不是存根:

http://pouchdb.com/adapters.html

在 NodeJS 中:

var PouchDB = require('pouchdb');

var testDB = new PouchDB('testDb', {
  db: require('memdown')
});

或在浏览器中:

<script src="pouchdb.js"></script>
<script src="pouchdb.memory.js"></script>
<script>
    // this pouch is ephemeral; it only exists in memory
   var testDB = new PouchDB('testDB', {
       adapter: 'memory'
   });
</script>

例如以这种方式测试的项目,请查看:https ://github.com/hoodiehq/pouchdb-hoodie-api/tree/master/tests

于 2015-09-09T20:44:09.053 回答