Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

node.js - Cannot handle exceptions generated by require() in jest.isolatemodule()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...