我有一个节点模块,在该模块中,我尝试用以下方式连接到主机:
const testConnection = net.createConnection(port, hostname);
testConnection.on('connect', () => {
// connected
});
testConnection.on('error', (err) => {
// error
});我正在使用Sinon来测试这样的方法:
sinon.stub(net, 'createConnection', (port, hostname) => {
return {
on: (string, cb) => {
switch(string) {
case 'connect':
return cb;
case 'error':
return cb;
case 'close':
return cb;
}
}
}
});
const testConnection = net.createConnection(10, 'hostname');
testConnection.on('error', () => {
console.log('here I am');
});但是,我无法理解我应该如何避免存根/模拟或假调用on-方法,这样它就会返回一个错误!
我是不是漏掉了什么?
发布于 2017-02-07 11:23:00
我会用一个假的createConnection实例来存根EventEmitter返回值:
const EventEmitter = require('events');
const fakeEE = new EventEmitter();
sinon.stub(net, 'createConnection', (port, hostname) => fakeEE);
// require your code
// emit events
fakeEE.emit('error', new Error('Smth bad happened'));
// observe the result
// e.g. expect(something).toBeCalled();发布于 2017-02-07 11:05:07
由于net是模块的依赖项,所以我会使用丙氧奎尔来伪造该依赖项。ES6 + Babel组合体对我们也很有用。
https://stackoverflow.com/questions/42087211
复制相似问题