Vis*_*ria 2 bdd unit-testing mocking jasmine angularjs
我想测试questionsBucket这个facotry
.factory('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
var questionsBucket = answersBucket;
var questionToRemove, answers, question;
var QA = {
answers: function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
},
question: function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
}
};
return QA;
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样,它questionsBucket是一个未在QA对象中返回的变量,我不希望它暴露于使用它的任何东西.
在Ruby中有很多方法可以获取这些数据或访问私有方法,但我看不到如何在Angular中完成它.
以下是我想在Jasmine中编写测试的方法.
it('should remove a question from the questionsBucket',
inject(function(QA){
var answers = QA.answers(5);
var question = Qa.question();
//I can't access the questionBucket :(
expect(QA.questionsBucket).toEqual(4);
}));
Run Code Online (Sandbox Code Playgroud)
如果您想在工厂中进行测试,请将其返回或返回功能以获取它.
.factory('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
var questionsBucket = answersBucket;
var questionToRemove, answers, question;
var QA = {
//return it-->
questionsBucket: questionsBucket,
//return a way to get it-->
getQuestionsBucket: function(){
return questionsBucket;
},
answers: function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
},
question: function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
}
};
return QA;
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用服务而返回questionsBucket作为服务的成员:
.service('QA', function(ShuffleArray, RandWords){
var answersBucket = RandWords.get(9);
this.questionsBucket = answersBucket;
var questionToRemove, answers, question;
this.answers= function(amount){
if(typeof(amount) === 'undefined') amount = 3;
answers = ShuffleArray.shuffle(answersBucket).slice(0,amount);
return answers;
};
this.question= function(){
questionToRemove = questionsBucket.indexOf(answers[Math.floor(Math.random() * 3)]);
question = questionsBucket.splice(questionToRemove, 1)[0];
return question;
};
});
Run Code Online (Sandbox Code Playgroud)
或者 - 您可以创建另一个服务/提供者/工厂并将其注入您的QA服务/工厂:
app.service('Buckets', function(RandWords){
this.answers = RandWords.get(9);
this.questions = answersBucket;
});
app.service('QA', function(ShuffleArray, Buckets){
this.answersBucket = Buckets.answers;
this.questionsBucket = Buckets.questions;
/*all the rest here - omitted for brevity*/
});
Run Code Online (Sandbox Code Playgroud)