Can ES6 constructors be stubbed more easily with Sinon?

后端 未结 1 801
旧时难觅i
旧时难觅i 2021-01-27 23:11

Given the (overly simplified) snippet:

import Validator from \'validator\';

export default function isValid(arg) {
  // Validator#isValid is an ES6 getter
  ret         


        
相关标签:
1条回答
  • 2021-01-27 23:39

    What you want isn't really possible. Stubbing requires some kind of "seam" through which to put the stubs in place. When you import functions (constructors or otherwise) directly in your production code, the only seam you're leaving is the import process itself.

    There is proxyquire, which overrides require calls in node. I don't know what environment you're using, and I don't really know how well this plays with ES6 modules. If you're transpiling to ES6 using babel, though, it should work.

    In my experience this kind of stuff is not worth the additional complexity. My usual workaround is to just make a static factory function and stub/use that instead of using the constructor directly:

    export default class Validator {
      constructor(arg) {
        this.innerValue = arg;
      }
    
      static create(arg) {
        return new Validator(arg);
      }
    
      get isValid() {
        return aFunctionOf(this.innerValue);
      }
    }
    

    If you want a unit test for the factory, you can simply check the returned instance instead of stubbing the constructor:

    it('create should return an instance', function() {
      let arg = { foo: 'bar' };
    
      let result = Validator.create(arg);
    
      expect(result).to.be.an.instanceof(Validator);
      expect(result.innerValue).to.equal(arg);
    });
    
    0 讨论(0)
提交回复
热议问题