2013-04-01 36 views
3

我有一個茉莉花測試失敗,因爲隨機數正在生成,這個隨機值是不同的執行和規格。茉莉花規格產生不同的隨機數比執行

fetch: function(options) { 
    if(typeof options === "undefined") { 
     options = {}; 
    } 
    if(typeof options.data === "undefined") { 
     options.data = {}; 
    } 
    options.data.id = this.journalId; 
    options.data.random = Math.floor(Math.random()*10000); 
    col.prototype.fetch.call(this, options); 
} 

以下測試失敗,因爲Math.floor(Math.random()*10000)正在生成不同的值。

it("should call parent fetch with default options", function() { 
    this.collection.fetch(); 
    expect(this.fetchSpy).toHaveBeenCalledWith({ 
    data: { 
     id: 1, 
     random: Math.floor(Math.random()*10000) 
    } 
    }); 
}); 

有沒有辦法讓我的測試通過的情況下,我有隨機數字被生成?

回答

6

您可以模擬Math.random功能。茉莉花2:

it("should call parent fetch with default options", function() { 
    spyOn(Math, 'random').and.returnValue(0.1); 
    this.collection.fetch(); 
    expect(this.fetchSpy).toHaveBeenCalledWith({ 
    data: { 
     id: 1, 
     random: Math.floor(Math.random()*10000) 
    } 
    }); 
}); 

茉莉花1:

it("should call parent fetch with default options", function() { 
    jasmine.spyOn(Math, 'random').andReturn(0.1); 
    this.collection.fetch(); 
    expect(this.fetchSpy).toHaveBeenCalledWith({ 
    data: { 
     id: 1, 
     random: Math.floor(Math.random()*10000) 
    } 
    }); 
}); 
0

如果你想模擬了一系列的 「隨機」 的價值觀,你可以使用:

spyOn(Math, 'random').and.returnValues(0.1, 0.2, 0.3, 0.4); 

請注意,您必須添加s換貨價值s或者它不會工作