Recently, I embarked on a journey to learn TypeScript and decided to test my skills by creating a simple app with jest unit testing (using ts-jest):
Here is the code snippet for the 'simple app.ts' module:
function greet(person: string): string {
return `Hello, ${person}`;
}
exports.greet = greet;
Additionally, here is the code for the 'simple app.spec.ts':
const greetObject = require('../app');
greetObject.greet(1);
describe('greet function', () => {
it('should return greeting', () => {
expect(greetObject.greet('Dude')).toEqual('Hello, Dude');
});
it('should throw type exception', () => {
const spy = jest.spyOn(greetObject, 'greet');
greetObject.greet(1);
/** @todo what should happen ? */
});
});
The burning question in my mind is: should I be getting a type error or not? Surprisingly, I did not encounter any errors in this scenario.
However, if I intentionally call the greet function with the wrong parameter type in the app.ts file, the entire test suite fails.
Could it be that I am overlooking something crucial in TypeScript unit testing?
Update: After converting require to ES6 import, TypeScript diagnostics started working. Yet, I remain unsure about how to handle incorrect types and test those scenarios effectively. Any guidance on this matter would be highly appreciated.