【问题标题】:Mock tests doesn't fail模拟测试不会失败
【发布时间】:2020-01-05 21:49:11
【问题描述】:

我正在使用 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.

测试应该失败,但通过了

【问题讨论】:

    标签: node.js mocking jestjs mockingoose


    【解决方案1】:

    您将收到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.',
        );
      });
    });
    

    【讨论】:

    • 真的很感谢!!!我刚刚学习编程和网络开发,你的解释给我留下了深刻的印象,谢谢!我希望有一天我能够将帮助回馈给社区,如果我的英语不好,请见谅。
    • 不客气,很高兴听到它有帮助! @Delm
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 2021-10-16
    • 2017-11-19
    • 2019-11-11
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多