我在使用MochaChaiMockgoose进行单元测试时超时

我有一个功能Assessment.NewAssessment(assessmentDetails),它将评估保存在数据库中。

注意:`Assessment.NewAssessment返回一个promise(它是一个异步函数)

这是我到目前为止所做的:

require('assert');
let chai = require('chai');
let chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
let expect = chai.expect;
let Assessment = require('../models/Assessment');
let CustomError = require('../CustomError');

let mongoose = new (require('mongoose').Mongoose)();
let Mockgoose = require('mockgoose').Mockgoose;
let mockgoose = new Mockgoose(mongoose);

before(function (done) {
    mockgoose.prepareStorage().then(async function () {
        mongoose.connect(
            'mongodb://127.0.0.1/' + process.env.DB_NAME + '_test?replicaSet=rs0',
            {useNewUrlParser: true},
            function (err) {
                done(err);
            });
    });
});

describe('Class Assessment', function () {
    describe('Function GetAll', function () {
        it('Throw an error with code 400 for non-object parameters', () => {
            return expect(Assessment.GetAll('test'))
                .to.be.eventually.rejectedWith(CustomError)
                .and.have.property('code', 400);
        });

        it('Successfully creating an assessment', async () => {
            let assessmentDetails = {
                name: 'test',
                createdBy: mongoose.Types.ObjectId(),
            };
            let assessment = await Assessment.NewAssessment(assessmentDetails)

            return expect(assessment).to.be.an('object');
        });
    });
});


Assessment.js中:

static async NewAssessment(assessmentDetails) {
    if (!assessmentDetails || typeof assessmentDetails !== 'object') {
        throw new CustomError('assessmentDetails is not defined.', HttpStatus.BAD_REQUEST);
    }

    return await new Assessment(assessmentDetails).save();
}


运行mocha --timeout 120000的输出是:

Error: Timeout of 120000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.


我在这里做错了什么?

最佳答案

我不知道为什么,但是有了这个:

it('Successfully creating an assessment', async () => {
    let assessmentDetails = {
        name: 'test',
        createdBy: mongoose.Types.ObjectId(),
    };

    return expect(Assessment.NewAssessment(assessmentDetails))
        .to.be.eventually.an('object');
);


一切正常。

关于node.js - 在Mocha和Chai-Expect中使用Mockgoose/Mongoose保存/创建时超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55701446/

10-16 20:48