简体   繁体   English

使用“异步等待”模式时,Mocha单元测试尚未完成

[英]Mocha unit test not finalized when using the 'async-await' pattern

Assume the following class in TypeScript: 假定TypeScript中的以下类:

class MongoDbContext implements IMongoDbContext {
    private connectionString : string;
    private databaseName : string;
    private database : Db;
    public constructor (connectionString : string, databaseName : string) {
        this.connectionString = connectionString;
        this.databaseName = databaseName;
    }

    public async initializeAsync () : Promise<MongoDbContext> {
        // Create a client that represents a connection with the 'MongoDB' server and get a reference to the database.
        var client = await MongoClient.connect(this.connectionString, { useNewUrlParser: true });
        this.database = await client.db(this.databaseName);

        return this;
    }
}

Now, I want to test if an exception is thrown when I'm trying to connect to an unexisting MongoDB server, this is done with the following integration test: 现在,我想测试在尝试连接到不存在的MongoDB服务器时是否引发异常,可通过以下集成测试来完成:

it('Throws when a connection to the database server could not be made.', async () => {
    // Arrange.
    var exceptionThrowed : boolean = false;
    var mongoDbContext = new MongoDbContext('mongodb://127.0.0.1:20000/', 'databaseName');

    // Act.
    try { await mongoDbContext.initializeAsync(); }
    catch (error) { exceptionThrowed = true; }
    finally {
        // Assert.
        expect(exceptionThrowed).to.be.true;
    }
}).timeout(5000);

When I run this unit test, my CMD window doesn't print a summary. 当我运行此单元测试时,我的CMD窗口不显示摘要。 It seems that it's hanging somewhere. 似乎它挂在某个地方。

What am I'm doing wrong in this case? 在这种情况下,我在做什么错?

Kind regards, 亲切的问候,

I've managed to find the issue. 我设法找到了问题。 It seems that I must close my 'MongoClient' connection for Mocha to quit correctly. 看来我必须关闭“ MongoClient”连接才能使Mocha正确退出。

So, I've added an extra method 所以,我添加了一个额外的方法

public async closeAsync () : Promise<void> {
    await this.client.close();
}

This method is called after each test. 每次测试后都会调用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM