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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32550115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:35:40  来源:igfitidea点击:

Mocking JavaScript constructor with Sinon.JS

javascriptnode.jsunit-testingmockingsinon

提问by krl

I'd like to unit test the following ES6 class:

我想对以下 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;

How do I mock constructor with Sinon.JS in order to mock getEventsof internalServiceto test getData?

我如何模拟构造与Sinon.JS以嘲笑getEventsinternalService测试getData

I looked at Javascript: Mocking Constructor using Sinonbut wasn't able to extract a solution.

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

// test.js
const chai = require('chai');
const sinon = require('sinon');
const should = chai.should();

let Service = require('service');

describe('Service', function() {
  it('getData', function() {
    // throws: TypeError: Attempted to wrap undefined property Service as function
    sinon.stub(Service, 'Service').returns(0);
  });
});

采纳答案by victorkohl

You can either create a namespace or create a stub instance using sinon.createStubInstance(this will not invoke the constructor).

您可以使用创建命名空间或创建存根实例sinon.createStubInstance(这不会调用构造函数)。

Creating a namespace:

创建命名空间:

const namespace = {
  Service: require('./service')
};

describe('Service', function() {
  it('getData', function() {
    sinon.stub(namespace, 'Service').returns(0);
    console.log(new namespace.Service()); // Service {}
  });
});

Creating a stub instance:

创建存根实例:

let Service = require('./service');

describe('Service', function() {
  it('getData', function() {
    let stub = sinon.createStubInstance(Service);
    console.log(stub); // Service {}
  });
});