I am testing a typescript project with ts-mockito and jest. Getting errors like this on a function called execute
:
Error: 'MyAbstractClass.execute' is not a function
// main.ts
abstract class MyAbstractClass {
abstract execute(arg): Promise<any>;
}
class MyImplementedClass extends MyAbstractClass {
execute(arg): Promise<any> {
// ... do some stuff
return foo;
}
}
// main.test.ts
describe(... {
let mockMyAbstractClass: MyAbstractClass;
let myAbstractClassInstance: MyAbstractClass;
beforeEach(() => {
mockMyAbstractClass = mock(MyAbstractClass);
myAbstractClassInstance = instance(mockMyAbstractClass);
});
it('works', async () => {
// ...
when(mockMyAbstractClass.execute(input)).thenResolve(output); // error is on this line
});
});
I've tried setting mocks on the prototype and using jest.fn() to help with mocking to no avail.
It seems like you need to define and instantiate your subclass for the mock to work:
// Before
let mockMyAbstractClass: MyAbstractClass;
let myAbstractClassInstance: MyAbstractClass;
beforeEach(() => {
mockMyAbstractClass = mock(MyAbstractClass);
myAbstractClassInstance = instance(mockMyAbstractClass);
});
// After
let mockMyAbstractClass: MyClass;
let myAbstractClassInstance: MyClass;
beforeEach(() => {
mockMyAbstractClass = mock(MyClass);
myAbstractClassInstance = instance(mockMyAbstractClass);
});