Consider two classes A
and B
like this:
class A {
private b: B;
public constructor(b: B){
this.b=b;
}
public doSomething(){
this.b.myMethod();
}
}
class B {
public myMethod(){...}
public someOtherMethod(){...}
}
I would like to Test class A
while mocking the behaviour of B.myMethod()
Currently we do this like this:
const bMock: Partial<B> = {
myMethod: jest.fn(<some mock here>),
}
const sut = new A(bMock as any);
sut.doSomething();
expect(bMock.myMethod).toBeCalled();
What we would like to achieve is a similar result but without having to pass the mock with as any
and without having to mock all methods on our own. Having the mock type checked is very important for us as otherwise we will not catch breaking changes in the mocked dependencies with this test.
We already had a look into sinon
as well, but in some cases we do not want the constructor of our mocked dependency to be invoked and thus stubbing the object after creation is not an option. Stubbing the whole class causes similar issues like described above.