2
votes

I have written some tests in TypeScript using the mocha testing framework and chai assertion library (I am new to all 3 of these), and saw that an error was thrown and assert.fail() was called in the code below. However, the test is still marked as passing. I am confused as to why that would happen, and if I am doing something wrong with promises. Also, as shown below, there is an UnhandledPromiseRejectionWarning. I don't understand why this is marked as unhandled as I have included a catch block. I would appreciate any advice on how to resolve this, thanks!

   User.all()
      .then((users) => {
        expect(users.length).to.equal(0);
        return User.create('[email protected]', '12345', 'test', true, true);
      })
      .then(() => {
        return User.all();
      })
      .then((users) => {
        expect(users.length).to.equal(1);
      })
      .catch((error) => {
        assert.fail();
      });

DEBUG CONSOLE

 ✓ should create a new record
  with existing e-mail in the database
(node:29903) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): AssertionError: assert.fail()
(node:29903) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Code

Debug Console

1
Put a return before the Users.all callBenjamin Gruenbaum
Thanks! Haha I just figured that out and was about to post, you beat me to it. I was reading this article (alisdair.mcdiarmid.org/…), and read "To write the test for this, make sure that your it block returns a promise, and mocha will take care of the rest:"Lauren

1 Answers

6
votes

As Benjamin Gruenbaum said above, this was fixed by making sure the it block returns a promise

it('should create a new record', () => {

   return User.all()
      .then((users) => {
        expect(users.length).to.equal(0);
        return User.create('[email protected]', '12345', 'test', true, true);
      })
      .then(() => {
        return User.all();
      })
      .then((users) => {
        expect(users.length).to.equal(1);
      })
     .catch((error) => {
       assert.fail();
     });
 });