gpt4 book ai didi

angularjs - 如何使用 Jasmine 在 Angular JS 工厂中测试变量

转载 作者:行者123 更新时间:2023-12-01 00:43:34 25 4
gpt4 key购买 nike

我想在这个工厂测试questionsBucket

.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;
});

如您所见,questionsBucket 是一个未在 QA 对象中返回的变量,我不希望它暴露给任何使用它的人。

在 Ruby 中有很多方法可以获取此数据或访问私有(private)方法,但我看不到如何在 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);

}));

最佳答案

如果你想在你的工厂测试它,返回它或者返回一个函数来获取它。

.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;
});

另一种选择是改用服务并将 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;
};
});

或者 - 您可以创建另一个服务/提供者/工厂并将其注入(inject)您的 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*/
});

关于angularjs - 如何使用 Jasmine 在 Angular JS 工厂中测试变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23781265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com