使用Sinon.JS模拟JavaScript构造函数

时间:2015-09-13 13:24:59

标签: javascript node.js unit-testing mocking sinon

我想对以下ES6课进行单元测试:

// service.js
const InternalService = require('internal-service');

class Service {
  constructor(args) {
    this.internalService = new InternalService(args);
  }

  getData(args) {   
    let events = this.internalService.getEvents(args);
    let data = getDataFromEvents(events);
    return data;
  }
}

function getDataFromEvents(events) {...}

module.exports = Service;

如何使用Sinon.JS模拟构造函数以模拟getEvents的{​​{1}}来测试internalService

我查看Javascript: Mocking Constructor using Sinon但无法提取解决方案。

getData

1 个答案:

答案 0 :(得分:-3)

由于sinon.createStubInstance已从最新版本的Sinon中删除,我建议在原型上隐藏单个实例方法,以达到预期效果。像这样:

const spy = sinon.stub(InternalService.prototype, 'getEvents').returns([{ id: 1 }]);
const internalService = new InternalService();
console.log(internalService.getEvents());
// => [{ id: 1 }]