Dob*_*bob 1 javascript node.js async-await jestjs ecmascript-2017
我正在学习使用最新的ecmascript语法为我的MongoDB后端代码进行的测试.我正在测试,如果我试图从空集合中找到一个文档,看看测试是否会通过测试.
光标应该是null结果,因为没有任何返回,这意味着光标是假的,但是即使我告诉它预期真实并且我不知道原因,下面的测试仍然通过:
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()
}
})
})
Run Code Online (Sandbox Code Playgroud)
另外,这是一个很好的测试测试风格吗?我在某处读到你不应该在测试中使用try/catch块.但这就是你用来处理异步/等待错误的方法.
不要使用async函数作为回调 - 因为回调不应该返回promises; 他们的结果将被忽略(并且不会处理拒绝).假设Jest知道如何处理promises,你应该将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()
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
527 次 |
| 最近记录: |