Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.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
Javascript Jest:如何在我的代码中测试错误路由_Javascript_Node.js_Unit Testing_Mocking_Jestjs - Fatal编程技术网

Javascript Jest:如何在我的代码中测试错误路由

Javascript Jest:如何在我的代码中测试错误路由,javascript,node.js,unit-testing,mocking,jestjs,Javascript,Node.js,Unit Testing,Mocking,Jestjs,我的ES6用户类中有以下函数,用于搜索给定字符串的用户 // Search for a user by their pNick, includes partial matching static getBypNick(pNick = '') { // Define our search criteria regex and normalise to lower case const userSearchRegex = new RegExp(`^${pNic

我的ES6用户类中有以下函数,用于搜索给定字符串的用户

// Search for a user by their pNick, includes partial matching
    static getBypNick(pNick = '') {
        // Define our search criteria regex and normalise to lower case
        const userSearchRegex = new RegExp(`^${pNick.toLowerCase()}`, 'i')

        return new Promise((resolve, reject) => {

            // Search user collection for pNick using regex like search and return array of results
            userTable.find({
                _pNick: userSearchRegex
            }).sort({
                _pNick: 1
            }).exec(function (err, result) {

                // If error reject
                if (err) {
                    return reject(err)
                }
                const userArray = result.map((user) => {
                    return new User(
                        user._pNick,
                        user._firstName,
                        user._userName,
                        user._phoneNumber,
                        user._userID)
                })
                // Return user records if found
                return resolve(userArray)
            })
        })
    }
虽然我可以使用Jest轻松测试成功路由,但我很难理解如何调用错误案例,尤其是函数中的.exec方法来调用promise中的拒绝路由

我知道我可以使用各种Jest特性,比如mockImplementation,但我就是想不出这个场景中的最佳情况。后台使用的数据库是NeDB,我非常肯定我只需要强制.exec部分返回一个错误,然后我应该在我的承诺中捕捉到这个

我无意测试底层的NeDB库,因为它有自己的测试,可以成功地执行,所以这实际上都是关于我自己的方法

我迄今为止的报道:
以下是单元测试解决方案:

userRepo.js

从“/userTable”导入{userTable};
从“/User”导入{User};
导出类UserRepo{
静态getBypNick(pNick=''){
const userSearchRegex=newregexp(`^${pNick.toLowerCase()}`,'i');
返回新承诺((解决、拒绝)=>{
用户表
.找到({
_pNick:userSearchRegex,
})
.分类({
_普尼克:1,
})
.exec(函数(错误、结果){
如果(错误){
退货拒绝(err);
}
const userArray=result.map((用户)=>{
返回新用户(用户。\点击,用户。\名字,用户。\用户名,用户。\电话号码,用户。\用户ID);
});
返回解析(userArray);
});
});
}
}
userTable.js

const userTable={
查找(){
归还这个;
},
排序(){
归还这个;
},
行政主任(新界北){
log('real exec');
fn();
},
};
user.js

导出类用户{
构造函数(尼克、名字、用户名、电话号码、用户名){
this.nick=nick;
this.firstName=firstName;
this.userName=用户名;
this.phoneNumber=电话号码;
this.userId=userId;
}
}
userRepo.test.js

从“/UserRepo”导入{UserRepo};
从“/userTable”导入{userTable};
jest.mock('./userTable',()=>{
常数mUserTable={
find:jest.fn().mockReturnThis(),
排序:jest.fn().mockReturnThis(),
exec:jest.fn(),
};
返回{userTable:mUserTable};
});
描述('47587358',()=>{
毕竟(()=>{
jest.resetAllMocks();
});
它('应该通过nick获取用户',异步()=>{
const mResult=[{{u pNick:''u pNick','u firstName:''u firstName','u userName:''u userName','u phoneNumber:123456,'u userID:1}];
userTable.exec.mockImplementationOnce((fn)=>{
fn(空,mResult);
});
const actual=await UserRepo.getBypNick('jest');
期望值(实际值)(
expect.arrayContaining([
expect.objectContaining({
尼克:期待。任何(字符串),
名字:expect.any(字符串),
用户名:expect.any(字符串),
电话号码:预期。任何(号码),
userId:expect.any(数字),
}),
]),
);
expect(userTable.find).toBeCalledWith({pNick:newregexp(`jest`,'i'));
expect(userTable.sort).toBeCalledWith({u pNick:1});
expect(userTable.exec).toBeCalledWith(expect.any(Function));
});
它('应该处理错误',异步()=>{
const mError=新错误(“网络”);
userTable.exec.mockImplementationOnce((fn)=>{
fn(mError,null);
});
wait expect(UserRepo.getBypNick('jest')).rejects.tothrower('network');
expect(userTable.find).toBeCalledWith({pNick:newregexp(`jest`,'i'));
expect(userTable.sort).toBeCalledWith({u pNick:1});
expect(userTable.exec).toBeCalledWith(expect.any(Function));
});
});
单元测试结果和覆盖率报告:

PASS src/stackoverflow/47587358/userRepo.test.js(9.448s)
47587358
✓ 应通过nick获取用户(10毫秒)
✓ 应处理错误(3ms)
-------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
-------------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 66.67 | 100 | 100 ||
user.js | 100 | 100 | 100 | 100 ||
userRepo.js | 100 | 66.67 | 100 | 100 | 5|
-------------|----------|----------|----------|----------|-------------------|
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:10.66秒


源代码:

您需要创建mock,该mock将返回特定测试的错误,这样您就可以使用mock,在测试期间将错误返回给您的代码,然后您可以在错误处理中验证代码,或者如果抛出了正确的异常等等…感谢@StevenScott的输入-您能提供一个创建此类模拟的示例吗?这就是我要讨论的问题。有几种方法可以做到这一点。有些是直接使用代码返回您需要返回的内容。我将遵循Jest文档,因为根据您需要的结果,有不同的方法来实现它。帮个大忙!非常感谢。