Node.js assert.throws with async functions (Promises)

后端 未结 5 683
失恋的感觉
失恋的感觉 2021-02-05 03:44

I want to check if an async function throws using assert.throws from the native assert module. I tried with

const test = async () => await aPromi         


        
5条回答
  •  囚心锁ツ
    2021-02-05 04:26

    You are going to want to use, assert.rejects() which is new in Node.js version 10.

    At the high level, instead of assert.throws, we want something like assert.rejects, hopefully you can take this and run with it:

            const assertRejects = (fn, options) => {
                return Promise.resolve(fn()).catch(e => {
                        return {
                            exception: e,
                            result: 'OK'
                        }
                    })
                    .then(v => {
    
                        if (!(v && v.result === 'OK')) {
                            return Promise.reject('Missing exception.');
                        }
    
                        if (!options) {
                            return;
                        }
    
                        if (options.message) {
                            // check options
                        }
    
                        console.log('here we check options');
    
                    });
            };
    
            it('should save with error', async () => {
    
                // should be an error because of duplication of unique document (see indexes in the model)
                return await assertRejects(async () => {
    
                    patientSubscriber = await PatientSubscriber.create({
                        isSubscribed: true,
                        patient: patient._id,
                        subscriber: user._id
                    });
    
                }, {
                    message: /PatientSubscriber validation failed/
                });
    
            });
    

提交回复
热议问题