簡體   English   中英

使用“異步等待”模式時,Mocha單元測試尚未完成

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

假定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;
    }
}

現在,我想測試在嘗試連接到不存在的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);

當我運行此單元測試時,我的CMD窗口不顯示摘要。 似乎它掛在某個地方。

在這種情況下,我在做什么錯?

親切的問候,

我設法找到了問題。 看來我必須關閉“ MongoClient”連接才能使Mocha正確退出。

所以,我添加了一個額外的方法

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

每次測試后都會調用此方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM