我正在学习Javascript并使用Jasmine进行测试。我有2个文件。文件有更多细节。这个特殊部分不起作用。当我运行测试时,它没有说“预期NAN等于10”。我想从Counter.js获取totalCount来计算MyProject.js,然后将其除以迭代。任何人都可以帮我这个吗?
Counter.js
function Counter(){
this.count = 0;
}
Counter.prototype.startCount = function(count){
this.count += count;
};
Counter.prototype.totalCount = function(){
return this.count;
}
MyProject.js
function MyProject() {
this.iteration = 0;
}
MyProject.prototype.addIteration = function(iteration) {
this.iteration += iteration;
}
MyProject.prototype.calculate = function() {
var averageCount = Counter.prototype.totalCount();
return averageCount/this.iteration;
}
MyProject_spec.js
describe("MyProject", function() {
var project, iteration1, iteration2, iteration3;
beforeEach(function(){
project = new MyProject();
iteration1 = new Counter();
iteration1.startCount(10);
iteration2 = new Counter();
iteration2.startCount(20);
iteration3 = new Counter();
iteration3.startCount(10);
});
it("can calculate(the average number of counting completed) for a set of iterations", function(){
project.addIteration(iteration1);
expect(project.calculate()).toEqual(10);
});
答案 0 :(得分:0)
当我进行测试时,它未能说"预期NAN等于10"
您的问题是addIteration
期待数字作为参数,并且您将Counter
传递给相同的人。
project.addIteration(iteration1);
您需要以
的方式修改MyProjectfunction MyProject()
{
this.allIteration = [];
this.totalIterationCount = 0;
}
MyProject.prototype.addIteration = function(iteration)
{
this.allIteration.push( iteration );
this.totalIterationCount += iteration.totalCount();
}
MyProject.prototype.calculate = function()
{
return this.totalIterationCount /this.allIteration.length;
}
<强>演示强>
function Counter() {
this.count = 0;
}
Counter.prototype.startCount = function(count) {
this.count += count;
};
Counter.prototype.totalCount = function() {
return this.count;
}
function MyProject() {
this.allIteration = [];
this.totalIterationCount = 0;
}
MyProject.prototype.addIteration = function(iteration) {
this.allIteration.push(iteration);
this.totalIterationCount += iteration.totalCount();
}
MyProject.prototype.calculate = function() {
return this.totalIterationCount / this.allIteration.length;
}
project = new MyProject();
iteration1 = new Counter();
iteration1.startCount(10);
iteration2 = new Counter();
iteration2.startCount(20);
iteration3 = new Counter();
iteration3.startCount(10);
project.addIteration(iteration1);
console.log(project.calculate());
project.addIteration(iteration2);
console.log(project.calculate());
project.addIteration(iteration3);
console.log(project.calculate());
&#13;