测试未通过。测试错误。小鸟。笑话

时间:2020-10-31 15:55:18

标签: node.js mongoose jestjs mocking mockingoose

我试图测试在创建没有必填字段的文档时是否抛出错误。

const { ShirtRepository } = require('../../../respositories');
const mockingoose = require('mockingoose').default;
const { Shirt, Comment } = require('../../../models');
let { ShirtModelMock: { shirt, shirts, likedShirt } } = require('../../mocks');

describe('Shirt Respository Tests', () => {

beforeEach(() => {
    Shirt.schema.path('comments', Object);
    mockingoose.resetAll();
    jest.clearAllMocks();
})


it('Should throw error when creating a shirt without required field', async () => {
    const _shirt = { ...shirt };

    delete _shirt.title;
    
    mockingoose(Shirt).toReturn(_shirt, 'save');

    const _shirtRepository = await new ShirtRepository({ Shirt });
    return await _shirtRepository.create(_shirt).catch(e => {
        expect(e.message).toBe('Shirt validation failed: title: titleIsRequired');

    });

    });
})

但是测试总是失败。.因为它抛出错误并且没有在测试中捕获错误。

 FAIL  src/tests/unit/repositories/shirt.repository.test.js
  Shirt Respository Tests
    ✓ Should return a shirt by id (33ms)
    ✓ Should return all shirts (2ms)
    ✓ Should delete a shirt by id (5ms)
    ✓ Should update a shirt by id (3ms)
    ✓ Should update a shirt when liked or dislked (18ms)
    ✓ Should create a shirt (7ms)
    ✕ Should throw error when creating a shirt without required field (7ms)

  ● Shirt Respository Tests › Should throw error when creating a shirt without required field

    ValidationError: Shirt validation failed: title: titleIsRequired

   at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:2626:32)
      at node_modules/mongoose/lib/document.js:2446:17
      at node_modules/mongoose/lib/schematype.js:1225:9

如何在不因该错误而失败的情况下“告诉”我期望该错误的测试?

我也尝试过:

    mockingoose(Shirt).toReturn(new Error('Error'), 'save');

但是还是一样。

我检查了这个this解决方案,但是没有用..我得到了相同的结果

0 个答案:

没有答案