Skip to content

Forbid node-style done callback in mocha it tests #8966

@jridgewell

Description

@jridgewell

Imagine code like this:

    it('test stuff', done => {
      unit.doSomething();
      setTimeout(() => {
        expect(somethingDoneAsync).equal('value');
        done();
      }, 0);
    });

But, there's a trap! If that expectation does not pass, we never hit the done callback and the assertion error will be swallowed!

The only appropriate way to use done callbacks in tests are:

// Promises. This is what we should be doing.
    it('test stuff', () => {
      unit.doSomething();
      return new Promise(resolve => {
        setTimeout(resolve, 0));
      }).then(() => {
        expect(somethingDoneAsync).equal('value');
      });
    });
// Node style. But why would you do this?
      setTimeout(() => {
        let error = null;
        try {
          expect(somethingDoneAsync).equal('value');
        } catch (e) {
          error = e;
        }
        done(error);
      }, 0);

Metadata

Metadata

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions