dimanche 17 mars 2019

Elegant way to fail async mocha test outside of describe

I have async code before my tests: Initing database connection etc, that I DON NOT want to move inside of each test case. For this I have to set --delay param to mocha.opts, and run run() function when test is ready to run. Well, currently it looks like this:

async myTest() {
  await prepare1();
  await prepare2();
  describe('1', async () => {
     it('11', async () => {
        await something();
     });
  });
  run();
}

myTest();

How do I fail test with mocha when statement prepare2() fails?

My attempts:

0) Just executing the function gives UnhandledPromiseRejectionWarning:

myTest(); 

1) this doesn't run test at all and exists with 0;

it('init', async () => {
    await myTest();
});

2) this says UnhandledPromiseRejectionWarning:

myTest().catch(e => {throw e});

3) with chai-as-promised: AssertionError: Promise should be fulfilled, UnhandledPromiseRejectionWarning:

assert.isFulfilled(myTest(), "Promise should be fulfilled");

4) The only thing that comes in mind is below. That doesn't seem to look nice with chai:

myTest().catch(e => {
    console.error(e);
    process.exit(1);
});

Aucun commentaire:

Enregistrer un commentaire