如何使用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
使用Sinon模拟这样的对象的正确方法是什么?
谢谢。
发布于 2018-05-29 08:26:24
如果你只是想测试给定的socket 'on‘方法在传入时是否被调用,你可以这样做:
my-class/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);
});
});
});https://stackoverflow.com/questions/50574383
复制相似问题