0

I'm making some tests using mookingose but they always pass even when showing some errors on the console,

This is an example of one of the tests

import mockingoose from 'mockingoose';
import { getUserById, insertUser } from '../controller/user';
import User from '../models/users';
import fetch from '../__mocks__/fetchnode';

describe('Test the user mongoose model', () => {
  beforeEach(() => {
    mockingoose.resetAll();
    jest.clearAllMocks();
  });

  it('should return a valid user with findById user', () => {
    mockingoose(User).toReturn(expectDoc, 'find');

    getUserById('507f191e810c19729de860ea').then(res => {
      expect(res.nickName).toBe(expectDoc.nickName);
    });
  });

  it('should return the user doc with Save user', () => {
    mockingoose(User).toReturn(expectDoc, 'save');

    insertUser(expectDoc).then(res => {
      expect(res.nickName).toBe(expectDoc.nickName);
    });
  });

  it('should return error message with invalid user doc to save user', () => {
    const OnlyAvatar = { avatar: expectDoc.avatar };
    mockingoose(User).toReturn(OnlyAvatar, 'save');

    insertUser(OnlyAvatar).catch(res => {
      expect(res.message).toBe(
        'AAAusers validation failed: name: Path `name` is required., nickName: Path `nickName` is required., email: Path `email` is required., password: Path `password` is required.',
      );
    });
  });
});

Right now I'm having errors like these on the console:

Expected: "AAAusers validation failed: name: Path `name` is required., nickName: Path `nickName` is required., email: Path `email` is required., password: Path `password` i
s required."
Received: "users validation failed: name: Path `name` is required., nickName: Path `nickName` is required., email: Path `email` is required., password: Path `password` is
 required."
(node:30984) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or
 by rejecting a promise which was not handled with .catch(). (rejection id: 2)
 PASS  src/routes/user.test.js

Test Suites: 5 passed, 5 total
Tests:       23 passed, 23 total
Snapshots:   0 total
Time:        3.057s
Ran all test suites matching /src\/routes\/category.test.js|src\/routes\/project.test.js|src\/routes\/task.test.js|src\/routes\/taskSearch.test.js|src\/routes\/user.test.
js/i.

The test should fail, but passes

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Delm
  • 67
  • 1
  • 9

1 Answers1

2

You are getting an UnhandledPromiseRejectionWarning.

That means a Promise is rejecting but the rejection isn't being handled.

Here is a highly simplified example demonstrating the issue:

test('a promise', () => {
  Promise.resolve().then(() => {
    expect(1).toBe(2);  // <= causes UnhandledPromiseRejectionWarning
  });
})

Since the test isn't waiting for the Promise to resolve, the test runs to completion and passes before the expect ever has a chance to run.

The then callback runs later and the expect fails causing the Promise to be rejected...but the test has already completed and nothing is handling the rejection.

Node detects the unhandled Promise rejection and displays the warning.

You always need to let Jest know when your test is asynchronous and either return the Promise:

test('a promise', () => {
  return Promise.resolve().then(() => {
    expect(1).toBe(2);  // <= fails as expected
  });
})

...use an async test function and await the Promise:

test('a promise', async () => {
  await Promise.resolve().then(() => {
    expect(1).toBe(2);  // <= fails as expected
  });
})

...or use done:

test('a promise', done => {
  Promise.resolve().then(() => {
    expect(1).toBe(2);  // <= fails as expected
    done();
  });
})

In your case the easiest fix is to return the Promise:

it('should return error message with invalid user doc to save user', () => {
  const OnlyAvatar = { avatar: expectDoc.avatar };
  mockingoose(User).toReturn(OnlyAvatar, 'save');

  return insertUser(OnlyAvatar).catch(res => {  // <= return the Promise
    expect(res.message).toBe(
      'AAAusers validation failed: name: Path `name` is required., nickName: Path `nickName` is required., email: Path `email` is required., password: Path `password` is required.',
    );
  });
});
Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • I'm really thankful!!! I'm just learning programming and web development and I'm really impressed with your explanation, thanks! I hope someday I'll be able to give back the help to the community, sorry if my english is no good. – Delm Sep 03 '19 at 04:02
  • you're welcome, glad to hear it was helpful! @Delm – Brian Adams Sep 03 '19 at 04:13