Correct way to use done() while testing asyc/await with mocha

前端 未结 1 525
悲哀的现实
悲哀的现实 2021-01-11 13:40

I am practicing basic unit test cases with mocha and a bit confused HOW and WHEN to use done() handler.

1条回答
  •  生来不讨喜
    2021-01-11 14:11

    The correct way is to not use done with async..await. Mocha supports promises and is able to chain a promise that is returned from it, etc. functions. And async function is syntactic sugar for a function that always returns a promise:

    it('Testing insertDocumentWithIndex', async () => {
        var data = await db.insertDocumentWithIndex('inspections', {
          "inspectorId" : 1,
          "curStatus" : 1,
          "lastUpdatedTS" : 1535222623216,
          "entryTS" : 1535222623216,
          "venueTypeId" : 1,
          "location" : [
            45.5891279,
            -45.0446183
          ]
        })
        expect(data.result.n).to.equal(1);
        expect(data.result.ok).to.equal(1);
    })
    

    done is needed only for testing asynchronous APIs than don't involve promises. Even then, converting to promises often results in cleaner control flow.

    And this

    it('Testing insertDocumentWithIndex', async () => {
      return new Promise(async (resolve, reject) => {
      ...
    

    is promise construction antipattern, which is even worse because of async promise constructor callback.

    These concerns also apply to other JS testing frameworks with similar API, Jest and Jasmine.

    0 讨论(0)
提交回复
热议问题