Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用Mocha为具有async await and try catch的函数编写适当的测试?_Node.js_Unit Testing_Async Await_Mocha.js_Try Catch - Fatal编程技术网

Node.js 如何使用Mocha为具有async await and try catch的函数编写适当的测试?

Node.js 如何使用Mocha为具有async await and try catch的函数编写适当的测试?,node.js,unit-testing,async-await,mocha.js,try-catch,Node.js,Unit Testing,Async Await,Mocha.js,Try Catch,我有一个从Mongodb获取所有作者的函数。我是测试新手,我自己花了数小时在网上尝试提出好的测试用例,但我真的不知道如何在这里正确地测试功能。errorHandler只是一个用于错误处理的类,wrap函数只是用描述来包装错误 const { MongoClient } = require('mongodb'); const credentials = require('../database-credentials'); const mongoClient = new M

我有一个从Mongodb获取所有作者的函数。我是测试新手,我自己花了数小时在网上尝试提出好的测试用例,但我真的不知道如何在这里正确地测试功能。errorHandler只是一个用于错误处理的类,wrap函数只是用描述来包装错误

    const { MongoClient } = require('mongodb');
    const credentials = require('../database-credentials');
    const mongoClient = new MongoClient(credentials.URI,{useUnifiedTopology: true });
    mongoClient.connect();
    const mongodb = mongoClient.db();

    async getAllAuthors (cb) {
        try {
            const result = await mongodb.collection('authors').find({}).toArray();
            return cb(null, result);
        } catch (error) {
            return cb(errorHandler.wrap(error, 'while fetching all authors in the book'));
        }
    }

您需要使用一个存根库,如
sinon.js
来存根副作用方法。对于您的情况,副作用方法是
mongodb.collection().find().toArray()
。每个测试用例应该只测试一个场景

以下是单元测试解决方案:

index.ts

const errorHandler={
包装(错误、消息){
控制台日志(消息);
返回误差;
},
};
导出默认类SomeClass{
mongodb;
构造函数(mongodb){
this.mongodb=mongodb;
}
异步getAllAuthors(cb){
试一试{
const result=wait this.mongodb
.collection('作者')
.find({})
.toArray();
返回cb(空,结果);
}捕获(错误){
返回cb(errorHandler.wrap(错误,“获取书中的所有作者时”);
}
}
}
index.test.ts

从“/”导入SomeClass;
从“sinon”进口sinon;
描述('59609593',()=>{
举个例子;
const Mongodbsub={
集合:sinon.stub().returnsThis(),
查找:sinon.stub().returnsThis(),
toArray:sinon.stub(),
};
在每个之前(()=>{
instance=newsomeclass(mongodbsub);
});
之后(()=>{
sinon.restore();
});
它('应该正确地找到作者',异步()=>{
const callback=sinon.stub();
解析([{id:1},{id:2}]);
等待instance.getAllAuthors(回调);
sinon.assert.calledWithJustice(mongodbsub.collection,'authors');
sinon.assert.calledWithJustice(mongodbsub.find,{});
sinon.assert.calledOnce(mongodbsub.toArray);
assert.calledWithJustice(回调,null,[{id:1},{id:2}]);
});
它('应该处理错误',异步()=>{
const callback=sinon.stub();
常量错误=新错误(“网络错误”);
MongodBSub.toArray.rejects(错误);
等待instance.getAllAuthors(回调);
sinon.assert.calledWithJustice(回调,错误);
});
});
100%覆盖率的单元测试结果:


59609593
✓ 应该正确地找到作者
在获取书中所有作者的同时
✓ 应该处理错误
2次通过(14毫秒)
---------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
---------------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
index.test.ts | 100 | 100 | 100 | 100 ||
index.ts | 100 | 100 | 100 | 100 ||
---------------|----------|----------|----------|----------|-------------------|

更新

如果使用
require
/
import
语句导入依赖项,例如
mongodb
包。以下是单元测试解决方案:

index-v2.js

const{MongoClient}=require('mongodb');
常量凭据={URI:'mongdb://127.0.0.1:27019' };
const mongoClient=new mongoClient(credentials.URI,{useUnifiedTopology:true});
mongoClient.connect();
const mongodb=mongoClient.db();
常量错误处理程序={
包装(错误、消息){
控制台日志(消息);
返回误差;
},
};
上课{
异步getAllAuthors(cb){
试一试{
const result=等待mongodb
.collection('作者')
.find({})
.toArray();
返回cb(空,结果);
}捕获(错误){
返回cb(errorHandler.wrap(错误,“获取书中的所有作者时”);
}
}
}
module.exports=SomeClass;
index-v2.test.js

const sinon=require('sinon');
const mongodb=require('mongodb');
描述('59609593',()=>{
const Mongodbsub={
connect:sinon.stub().returnsThis(),
db:sinon.stub().returnsThis(),
集合:sinon.stub().returnsThis(),
查找:sinon.stub().returnsThis(),
toArray:sinon.stub(),
};
举个例子;
之前(()=>{
sinon.stub(mongodb,‘MongoClient’).callsFake(()=>mongodbsub);
const SomeClass=require('./index-v2');
instance=newsomeclass();
});
之后(()=>{
sinon.restore();
});
它('should find authors',async()=>{
解析([{id:1},{id:2}]);
const callback=sinon.stub();
等待instance.getAllAuthors(回调);
sinon.assert.calledWithJustice(mongodbsub.collection,'authors');
sinon.assert.calledWithJustice(mongodbsub.find,{});
sinon.assert.calledOnce(mongodbsub.toArray);
assert.calledWithJustice(回调,null,[{id:1},{id:2}]);
});
它('应该处理错误',异步()=>{
const callback=sinon.stub();
常量错误=新错误(“网络错误”);
MongodBSub.toArray.rejects(错误);
等待instance.getAllAuthors(回调);
sinon.assert.calledWithJustice(回调,错误);
});
});
100%覆盖率的单元测试结果:

59609593
✓ 应该找到作者
在获取书中所有作者的同时
✓ 应该处理错误
2次通过(74毫秒)
------------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
------------------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 100 | 100 ||
索引-v2.js | 100 | 100 | 100 | 100 ||
index-v2.test.js | 100|