Mocking JavaScript constructor with Sinon.JS

后端 未结 1 1831
无人共我
无人共我 2021-01-01 10:16

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

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

class Service {
  constructor(args) {
          


        
相关标签:
1条回答
  • 2021-01-01 10:42

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

    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 {}
      });
    });
    
    0 讨论(0)
提交回复
热议问题