简体   繁体   中英

Sinon Stub the whole class

I have the below class in A.js file,

class A {
    constructor(name) {
        this.name = name;
    }

    getResult() {
        return this.name;
    }
}

module.exports = A

In other file called controller.js , I'm using like this,

const A = require('./A');

module.exports = {
    doProcess: () => {
        const a = new A('John');

        console.log(a.getResult());
    }
}

So my requirement is, I want to stub the class A and its methods while writing the unit tests for controller.js . How can I achieve this using sinon?

Something like,

const getResultStub = sinon.stub();
getResultStub().returns('success');

If it is default export, I don't believe you can directly stub it.

If you are working in nodejs environment, You can either use proxyquire , or do something like:

// A.js

class A {
    constructor(name) {
        this.name = name;
    }

    getResult() {
        return this.name;
    }
}

module.exports = A
// controller.spec.js

const sinon = require('sinon')

class DummyA {
  constructor(){}
  getResult(){
    return 'success'
  }
}

require.cache[require.resolve('./A')] = DummyA

const controller = require('./controller.js')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM