如何在Node.js模块中监视类方法

用户名

我有一个导出类的简单模块:

function PusherCom(options) {
}

PusherCom.prototype.lobbyEvent = function(event, message) {
};

module.exports = PusherCom;

我从我的要求./index.js

var PusherCom = require('../comms/pusher');

function Play() {
  var pusher = new PusherCom();
  pusher.lobbyEvent('event', {});
}

我对此应用程序进行了测试,问题是如何模拟require('../comms/pusher')类或lobbyEvent方法。最好是有一个sinon间谍,因此我可以断定的参数lobbyEvent

describe 'playlogic', ->

  beforeEach, ->
    pushMock = ->
      @lobbyEvent = (event, message) ->
        console.log event
      @
    // currently I tried proxyquire to mock the require but it doesn't support spying
    proxyquire './index.js, { './comms/pusher': pushMock }

  it 'should join lobby', (done) ->
    @playLogic = require './index.js'
    @playLogic.joinedLobby {}, (err, result) ->
      // How can I spy pushMock so I can assert the arguments
      // assert pushMock.called lobbyEvent with event, 'event'

如何在Node.js中任意模块内的类中模拟/监视方法?

锻炼

我不是JavaScript专家,但无论如何我都会把握机会。对于您的情况而言,不是侦听模块,而是lobbyEvent()使用pusher实例方法来执行该模块并将其注入该模块Play()中是合理的解决方案?例如

// pusher.js
function PusherCom(options) { }

PusherCom.prototype.lobbyEvent = function(event, message) { };

module.exports = PusherCom;


// play.js
function Play(pusher) {
  pusher.lobbyEvent("event", { a: 1 });
}

module.exports = Play;

// play_test.js
 var assert    = require("assert"),
     sinon     = require("sinon"),
     PusherCom = require("./pusher"),
     Play      = require("./play");

describe("Play", function(){
  it("spy on PusherCom#lobbyEvent", function() {
    var pusher = new PusherCom(),
        spy    = sinon.spy(pusher, "lobbyEvent");

    Play(pusher);

    assert(spy.withArgs("event", { a: 1 }).called);
  })
})

HTH!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何在Node JS中获取对象的类名

来自分类Dev

测试模块中的node.js类

来自分类Dev

如何在$ HOME / bin下安装Node.js模块

来自分类Dev

如何在Node.js模块中监视类方法

来自分类Dev

如何在Node JS中模块化代码

来自分类Dev

如何在Webstorm中设置文件监视程序以重新启动Node.js?

来自分类Dev

如何在node.js中搜索?

来自分类Dev

如何在Node JS中打印对象

来自分类Dev

如何在内部调用的模块中存根或监视外部方法?

来自分类Dev

如何在Node js中创建图像?

来自分类Dev

如何在Node.js Lambda中使用请求模块

来自分类Dev

如何在Node.js中构造导入的类?

来自分类Dev

如何在Node上安装串口模块?

来自分类Dev

如何在模块中调用特定于类的方法

来自分类Dev

如何在Node.js中导入util模块?

来自分类Dev

如何在Node.JS中正确编写模块?

来自分类Dev

如何在Node.js中卸载npm模块?

来自分类Dev

如何在Node中覆盖其他模块方法

来自分类Dev

如何在node.js中导出模块

来自分类Dev

如何在Kiwi中监视类方法?

来自分类Dev

如何在PHP中模块化类方法?

来自分类Dev

如何在node.js服务中调用POST方法?

来自分类Dev

如何在Node.js中要求类

来自分类Dev

如何在JS中基于CSS类插入Node?

来自分类Dev

如何在Node JS中执行forloop

来自分类Dev

如何在node.js中创建异步方法链?

来自分类Dev

如何在 node.js 模块中嵌入承诺?

来自分类Dev

如何在 Node.js 中对 MongoDB 使用 populate 方法?

来自分类Dev

如何在 Node js 中添加会话