node.js - 单元测试不可用的全局函数(couchapp、mocha)

标签 node.js couchdb mocha.js

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

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

然后我可以很容易地将这个文件引入 mocha 测试。

问题是 CouchDB 公开了一些映射函数使用的全局函数(上面的“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 因全局泄密投诉而失败。

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

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

有什么想法吗?

最佳答案

我会使用 sinon 对测试进行 stub 和监视。 http://sinonjs.org/https://github.com/domenic/sinon-chai

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

您没有测试 CouchDb 的发出,因此您应该 stub ,因为 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" }));
});

希望对您有所帮助。

关于node.js - 单元测试不可用的全局函数(couchapp、mocha),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15399908/

相关文章:

arrays - Node.js:创建 8 字节缓冲区

node.js - HTTP2/SPDY推流验证 : How to Test?

node.js - NodeJS 未定义消息变量

node.js - Node.js 中的 Couchdb

Javascript:同步执行

javascript - 我对WebRTC协议(protocol)的理解正确吗?

java - 如何通过 Apache 的 HttpClient 在 Couchdb 中设置管理员(给出一个 curl 示例)

authentication - 允许非管理员用户创建 CouchDB 数据库

node.js - Webdriver - 如何通过 xpath/css 访问某些特定的 iFrame

javascript - Flux + Sinon + Promises 测试总是通过或超时