I have a typescript file that is meant to be run standalone:
(async () => {
try {
const notificationService = new NotificationService();
notificationService.notify('test');
} catch (err) {
logger.error(err, `error while running ${SERVICE_NAME}`);
process.exit(1);
}
})();
I'm wondering how can I test this using jest such as asserting that the notify() is called.
I don't think it possible to test a file like this. Functions and classes can be tested easily, however. The general guideline is that if it's hard to test you should refactor.
So instead how about you refactor that into a named and exported function.
export async bootNotificationService() {
try {
const notificationService = new NotificationService();
notificationService.notify('test');
} catch (err) {
logger.error(err, `error while running ${SERVICE_NAME}`);
process.exit(1);
}
}
Now you can import that function, mock jest.spyOn(process, 'exit')
, possibly mock NotificationService
, and then run the function.
And wherever this code used to be can now be replaced by:
import bootNotificationService from './boot-notification-service'
bootNotificationService()
This file you can't easily test, but at least you can test the code this file invokes.