sinon存根不工作

sinon stub is not working

我是测试的新手,我似乎没有成功地对一个函数进行存根。我试图存根连接到数据库,但它一直在联系它,而不是使用存根的结果:

函数如下:

var self = module.exports = {
VerifyAuthentication: function (data){      
    var deferred = q.defer()                
    if(typeof(data.email)=='undefined'){
        deferred.reject({data:{},errorcode:"",errormessage:"param 'email' is mandatory in input object"})
    }else{
        if(typeof(data.password)=='undefined'){
            deferred.reject({data:{},errorcode:"",errormessage:"param 'password' is mandatory in input object"})
        }else{
            var SqlString = "select id, mail, password, origin from tbl_user where mail = ?"    
            var param = [data.email]
            self.ExecuteSingleQuery(SqlString, param).then(function(results){   
                if(results.length > 0)
                {
                    if (results[0].password == data.password)
                    {                   
                        deferred.resolve({data:{"sessionId":results[0].id},errorcode:"",errormessage:""})
                    }else{              
                        deferred.reject({data:{},errorcode:"",errormessage:"bad password"})
                    }
                }else{
                    deferred.reject({data:{},errorcode:"",errormessage:"unknown user"})
                }
            })
        }
    }
    return deferred.promise
},
ExecuteSingleQuery: function (queryString, parameters){     
    var deferred = q.defer()        
    var connection = connect()

    connection.query(queryString, parameters, function (error, results, fields){
        if(error){ deferred.reject(error)};     
        deferred.resolve(results)
    });

    return deferred.promise
},

这是测试:

var dbconnection = require('../lib/dbConnection.js') 
describe("VerifyAuthentication", function(){
    it("_Returns DbResult object when user name and password match", function(){
        var expectedResult = {data:{"sessionKey":"b12ac0a5-967e-40f3-8c4d-aac0f98328b2"},errorcode:"",errormessage:""}
        stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').returns(Promise.resolve(expectedResult))
        return dbconnection.VerifyAuthentication({email:"correct@adres.com",password:"gtffr"}).then((result)=>{
            expect(result.data.sessionId).to.not.be.undefined
            expect(result.errorcode).to.not.be.undefined
            expect(result.errormessage).to.not.be.undefined
            stub.restore()                
        })
    })  
})

我总是报错'unknown user',这很正常,因为用户确实不在数据库中。但是,我想存根 'ExecuteSingleQuery' 函数,避免它连接到数据库。

我已经修复了您的代码中的几个问题,并将更正后的文件发布在下方。

dbConnection.js

var self = module.exports = {
    VerifyAuthentication: function (data) {
        var deferred = q.defer();

        if (typeof (data.email) == 'undefined') {
            deferred.reject({
                data: {},
                errorcode: '',
                errormessage: "param 'email' is mandatory in input object"
            });
        } else {
            if (typeof (data.password) == 'undefined') {
                deferred.reject({
                    data: {},
                    errorcode: '',
                    errormessage: "param 'password' is mandatory in input object"
                });
            } else {
                var SqlString = 'select id, mail, password, origin from tbl_user where mail = ?';
                var param = [data.email];

                self.ExecuteSingleQuery(SqlString, param).then(function (results) {
                    if (results.length > 0) {
                        if (results[0].password === data.password) {
                            deferred.resolve({
                                data: {
                                    'sessionId': results[0].id
                                },
                                errorcode: '',
                                errormessage: ''
                            });
                        } else {
                            deferred.reject({
                                data: {},
                                errorcode: '',
                                errormessage: 'bad password'
                            });
                        }
                    } else {
                        deferred.reject({
                            data: {},
                            errorcode: '',
                            errormessage: 'unknown user'
                        });
                    }
                });
            }
        }
        return deferred.promise;
    },
    ExecuteSingleQuery: function (queryString, parameters) {
        var deferred = q.defer();
        var connection = connect();

        connection.query(queryString, parameters, function (error, results, fields) {
            if (error) {
                deferred.reject(error);
            }
            deferred.resolve(results);
        });

        return deferred.promise;
    }
};

dbConnection.test.js

describe('VerifyAuthentication', function () {
    it('Returns DbResult object when user name and password match', function () {
        var expectedResult = [{
            id: '123',
            password: 'gtffr'
        }];

        const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult);

        return dbconnection.VerifyAuthentication({
            email: 'correct@adres.com',
            password: 'gtffr'
        }).then((result) => {
            expect(result.data.sessionId).to.not.be.undefined;
            expect(result.errorcode).to.not.be.undefined;
            expect(result.errormessage).to.not.be.undefined;
            stub.restore();
        });
    });
});

我在下面概述了有问题的部分:

  • expectedResult 变量的值类型错误。在里面 self.ExecuteSingleQuery() 实现检查长度 > 0 的数组。由存根编辑的固定结果 return 是一个对象而不是数组,这这就是为什么它 return 编辑了 未知用户 异常
  • 该数组应包含一个具有 { id: 'xxx', password: 'gtffr' } 属性的对象。根据 dbconnection.VerifyAuthentication({email:"correct@adres.com",password:"gtffr"}) 调用
  • 使用的密码验证密码
  • 最后,我将存根语句更改为 resolve 而不是 return,如此处所示 const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - 这是解决承诺的首选方法