2017-10-19 63 views
0

我在學習Javascript並使用Jasmine進行測試。我有2個文件。有更多的細節文件。這個特定的部分不起作用。當我運行測試時,它沒有說「預計NAN等於10」。我想從Counter.js獲得totalCount來計算MyProject.js,然後它被迭代分割。誰能幫我這個?如何從一個JavaScript文件獲取原型方法的值到另一個JavaScript文件的原型方法?

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

當我運行測試,它沒有說「預計NAN平等10「

您的問題是addIteration期待號碼作爲參數,並且您將Counter傳遞給相同。

project.addIteration(iteration1); 

您需要修改MyProject的這樣一種方式,

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

演示

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

相關問題