When it comes to writing my testing files in TypeScript, I rely on ts-jest
and jest
.
I'm facing some confusion regarding how to type the mock function of a module.
Let's take a look at the code:
./module.ts
:
import {IObj} from '../interfaces';
const obj: IObj = {
getMessage() {
return `Her name is ${this.genName()}, age is ${this.getAge()}`;
},
genName() {
return 'novaline';
},
getAge() {
return 26;
}
};
export default obj;
./module.test.ts
:
import * as m from './module';
describe('mock function test suites', () => {
it('t-1', () => {
// Unsure about the correct jest.Mock<string> type here.
m.genName: jest.Mock<string> = jest.fn(() => 'emilie');
expect(jest.isMockFunction(m.genName)).toBeTruthy();
expect(m.genName()).toBe('emilie');
expect(m.getMessage()).toEqual('Her name is emilie, age is 26');
expect(m.genName).toHaveBeenCalled();
});
});
How can I properly type the mock function genName
of module m
?
TypeScript
throws an error in this line:
Error:(8, 7) TS2540:Cannot assign to 'genName' because it is a constant or a read-only property.