2017-04-13 56 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() 
    } 
});