Reputation: 3366
I have class A
that extends from class B
:
A = class A
...
my_inner_func: (param1) =>
return new MyHelper()
B = class B extends A
...
In the unittest, my_inner_func()
should return MyMockHelper()
.
a = rewire './a.coffee'
b = rewire './b.coffee'
a.__set__
MyHelper: MyMockHelper
b.__set__
A: a.A
But B().my_inner_func()
returns MyHelper
instead of MyMockHelper
.
How does one mock a module used by an extended class in CoffeeScript (or JavaScript)?
Upvotes: 1
Views: 1210
Reputation: 12552
The documentation for rewire doesn't say anything about class instance variables. I think its really just for "rewiring" the globals or top-level scope of the module under test.
Also, rewire has a few limitations. Among them, support for const or babel seems to be ify, so perhaps try a native solution?
At a basic level, a mock is simply overriding or replacing a method on an object's prototype, so something like this should work in your test case
// super class
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
// superclass instance
const rect = new Polygon(10, 2);
console.log('rect', rect.area); // 20
// subclass
class Square extends Polygon {
constructor(side) {
super(side, side)
}
}
// subclass instance
const square = new Square(2);
console.log('square', square.area); // 4
// mocked calcArea of subclass
square.calcArea = function() {
return 0;
};
// result from new mocked calcArea
console.log('mocked', square.area); // 0
using mocha might look like this...
import Square from './Square';
describe('mocks', () => {
it('should mock calcArea', () => {
const square = new Square(2);
square.calcArea = function() {
return 0;
};
expect(square.area).to.equal(0);
});
});
Here's a code pen to play around with
Upvotes: 2