This is the code I want to test:
mongoose
.connect(dbUrl, { useNewUrlParser: true })
.then(({ connection }) => {
console.info(`Main database connected to ${connection.host} on port ${connection.port}`);
})
.catch((error) => {
throw new Error(`Main database connection error: ${error}`);
});
For some reasons, I need to intercept the error when the module is required. So I mocked mongoose and wrote my test (simplified):
const run = async () => {
let App;
try {
jest.isolateModules(() => {
App = require('@App/index');
});
} catch (_e) {
return true;
}
};
it('throws error if db connection fails', async () => {
mongoose.connect.mockImplementation(() => Promise.reject());
const error = await run();
expect(error).toBeTruthy();
});
All my tests runs well, except for those that should intercepts unhandled errors
I tried:
- intercept the exception with process.on('uncaughtException', /.../) and unhandledRejection
- use a try catch block around require('@App/index')
- Override Promise.prototype.catch (I was desperate)
I think jest.isolateModules creates some kind of isolated environment where I cannot access/modify, but I cannot understand how I can change this behavior
question from:
https://stackoverflow.com/questions/66048332/cannot-handle-exceptions-generated-by-require-in-jest-isolatemodule 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…