2017-04-13 60 views
0

我正在學習使用最新的ecmascript語法對我的MongoDB後端代碼進行笑話測試。我現在正在測試如果我試圖從空集合中找到文檔,那麼測試是否會通過測試。nodejs異步/等待嘗試/捕獲笑話測試通過時不應該

光標應該null,結果因爲沒有返回,這意味着光標falsey,但是當我告訴它期望truthy,我不知道下面還測試通過,甚至爲什麼:

import config from './config' 
const mongodb = require('mongodb') 

it('sample test',() => { 
    mongodb.MongoClient.connect(config.mongodb.url, async (connectErr, db) => { 
    expect(db).toBeTruthy() 
    let cursor 
    try { 
     cursor = await db.collection('my_collection').findOne() 
     // cursor is null, but test still passes below 
     expect(cursor).toBeTruthy() 
    } catch (findErr) { 
     db.close() 
    } 
    }) 
}) 

此外,這是一個很好的測試測試風格?我在某處讀過,你不應該在測試中使用try/catch塊。但是,這是你將用來處理異步/等待錯誤。

回答

5

請勿使用async函數作爲回調 - 因爲回調不應返回promise;他們的結果將被忽略(並且拒絕將不會被處理)。假設Jest知道如何處理promise,你應該將async函數傳遞給it本身。

it('sample test', async() => { 
    const db = await mongodb.MongoClient.connect(config.mongodb.url); 
    expect(db).toBeTruthy(); 
    try { 
    const cursor = await db.collection('my_collection').findOne(); 
    expect(cursor).toBeTruthy(); 
    } finally { // don't `catch` exceptions you want to bubble 
    db.close() 
    } 
});