sinon存根不起作用

时间:2017-05-02 07:56:18

标签: testing mocha sinon stub

我安静地进入测试阶段并且我似乎没有成功地成功完成一项功能。我试图将数据库的连接存根,但它一直在联系它,而不是使用存根的结果:

这里的功能是:

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()                
        })
    })  
})

我总是收到错误'未知用户'这是正常的,因为用户确实不在数据库中。但是,我想要存根' ExecuteSingleQuery'功能,避免它连接到DB。

1 个答案:

答案 0 :(得分:1)

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

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.存根返回的固定结果是对象而不是数组,这就是它返回未知用户异常的原因
  • 数组应包含具有{ id: 'xxx', password: 'gtffr' }属性的对象。密码将根据dbconnection.VerifyAuthentication({email:"correct@adres.com",password:"gtffr"})调用
  • 使用的密码进行验证
  • 最后,我已将stub语句更改为解决而非返回,如此处所示const stub = sinon.stub(dbconnection, 'ExecuteSingleQuery').resolves(expectedResult); - 这是解决承诺的首选方法