【问题标题】:Sinon: Mocking websockets/wsSinon:模拟 websockets/ws
【发布时间】:2018-05-28 23:11:54
【问题描述】:

如何使用 Sinon 模拟 websockets/ws?我正在尝试测试我的应用程序在使用 WebSockets 时是否按预期运行,而不必每次都连接(例如:测试事件处理程序等)。

来自 C# 背景,我只是使用像 Moq 这样的库来模拟整个界面,然后验证我的应用程序是否进行了预期的调用。

但是,当我尝试使用 Sinon 执行此操作时,我遇到了错误。

测试示例:

const WebSocket = require('ws');
const sinon = require('sinon');
const webSocket = sinon.mock(WebSocket);
webSocket.expects('on').withArgs(sinon.match.any, sinon.match.any);
const subject = new MyClass(logger, webSocket);

这个类然后调用:

this._webSocket.on("open", () => {
    this.onWebSocketOpen();
});

但是当我尝试运行我的测试时,我得到了这个错误:

TypeError: Attempted to wrap undefined property on as function

使用诗乃模拟这样的对象的正确方法是什么?

谢谢。

【问题讨论】:

    标签: node.js unit-testing mocking sinon


    【解决方案1】:

    如果您只是想测试在传入时是否调用了给定的套接字 'on' 方法,您会这样做:

    我的班级/index.js

    class MyClass {
      constructor(socket) {
        this._socket = socket;
    
        this._socket.on('open', () => {
          //whatever...
        });
      };
    };
    
    module.exports = MyClass;
    

    my-class/test/test.js

    const chai = require('chai');
    const expect = chai.expect;
    const sinon = require('sinon');
    const sinon_chai = require('sinon-chai');
    const MyClass = require('../index.js');
    const sb = sinon.sandbox.create();
    chai.use(sinon_chai);
    
    describe('MyClass', () => {
      describe('.constructor(socket)', () => {
        it('should call the .prototype.on method of the given socket\n \t' +
            'passing \'open\' as first param and some function as second param', () => {
          var socket = { on: (a,b) => {} };
          var stub = sb.stub(socket, 'on').returns('whatever');
          var inst = new MyClass(socket);
          expect(stub.firstCall.args[0]).to.equal('open');
          expect(typeof stub.firstCall.args[1] === 'function').to.equal(true);
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多