模拟测试不会失败

时间:2019-09-03 01:30:40

标签: node.js mocking jestjs mockingoose

我正在使用mookingose进行一些测试,但是即使在控制台上显示一些错误,它们也始终会通过

这是其中一项测试的示例

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.',
      );
    });
  });
});

现在我在控制台上遇到类似以下错误:

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.

测试应该失败,但是通过

1 个答案:

答案 0 :(得分:2)

您收到UnhandledPromiseRejectionWarning

这意味着Promise正在拒绝,但未处理拒绝。

以下是一个高度简化的示例,演示了此问题:

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

由于测试不等待Promise解决,因此测试运行完成并在expect有机会运行之前通过。

then回调稍后运行,并且expect失败,导致Promise被拒绝...但是测试已经完成,没有任何东西可以处理拒绝。

Node检测到未处理的Promise拒绝并显示警告。

您始终需要let Jest know when your test is asynchronous并返回Promise

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

...使用async测试函数和await Promise

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

...或使用done

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

对于您而言,最简单的解决方法是返回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.',
    );
  });
});