3

我正在尝试对 CouchDB 设计文档(使用couchapp.js编写)进行单元测试,例如:

var ddoc = {
  _id: '_design/example',
  views: {
    example: {
      map: function(doc) {
        emit(doc.owner.id, contact);
      }
    }
   }
}
module.exports = contacts

然后我可以很容易地将此​​文件要求到 mocha 测试中。

问题是CouchDB 暴露了一些map 函数使用的全局函数(上面的“emit”函数),这些函数在CouchDB 之外不可用(即在这些单元测试中)。

我试图在每个测试中声明一个全局函数,例如:

var ddoc = require('../example.js')

describe('views', function() {
  describe('example', function() {
    it('should return the id and same doc', function() {
      var doc = {
        owner: {
          id: 'a123456789'
        }
      }

      // Globally-scoped mocks of unavailable couchdb 'emit' function
      emit = function(id, doc) {
        assert.equal(contact.owner.id, id);
        assert.equal(contact, doc);
      }
      ddoc.views.example.map(doc);
    })
  })
})

但摩卡因抱怨全球泄漏而失败。

所有这一切都开始“闻起来不对劲”,所以想知道是否有更好/更简单的方法通过任何库,甚至在 Mocha 之外?

基本上我想让每个测试都可以使用模拟实现,我可以从中调用断言。

有任何想法吗?

4

1 回答 1

0

我会使用 sinon 来存根和监视测试。http://sinonjs.org/https://github.com/domenic/sinon-chai

全局变量很好,不受欢迎,但很难消除。我现在正在做一些与 jQuery 相关的测试,并且必须--globals window,document,navigator,jQuery,$在我的 mocha 命令行末尾使用,所以......是的。

您没有测试 CouchDb 的发射,因此您应该对它进行存根,因为 a)您假设它有效并且 b)您知道它将返回什么

global.emit = sinon.stub().returns(42);
// run your tests etc
// assert that the emit was called

sinon 文档的这一部分可能会有所帮助:

it("makes a GET request for todo items", function () {
    sinon.stub(jQuery, "ajax");
    getTodos(42, sinon.spy());

    assert(jQuery.ajax.calledWithMatch({ url: "/todo/42/items" }));
});

希望有帮助。

于 2013-03-27T17:43:12.977 回答