rewire
rewire copied to clipboard
Rewire a parent class
Hello, I need to rewire a parent class (ES6 syntax) but with the standard way it doesn't seem to work. Using mocha + sinon, here's my situation
Parent class
class Parent {
save() {
throw new Error('Unable to save');
}
}
Child class
class Child extends Parent {
static aMethod() {
Child.save()
}
}
Parent Mock
class parentMock {
save() {
throw new Error('mock error');
}
}
Test
var parentMock = require('./parentMock')
var Child = rewire('./child')
describe("#aMethod", function() {
before(function() {
Child.__set__('Parent', parentMock);
}
it('should do something', function() {
try {
Child.aMethod()
catch (e) {
expect(e.message).to.eqls('mock error) // fails with error 'Unable to save'
}
}
}
A simple workaround is to stub the save()
method with sinon in before
function
sinon.stub(Child.prototype, 'save', function() { // this behavior correctly overrides })
but this approach forces me to manually stub the class in tests every time it is extended. Am I missing something? Am I doing something wrong or it is a known issue? Thank you