Jasmine规范生成不同的随机数而不是执行

Huy*_*Huy 4 javascript testing tdd ruby-on-rails jasmine

我有一个失败的Jasmine测试,因为正在生成一个随机数,这个随机值对于执行和规范是不同的.

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);
}
Run Code Online (Sandbox Code Playgroud)

下面的测试失败,因为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) 
    }
  }); 
});
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的测试通过我生成随机数的情况?

Val*_*sin 7

你可以模拟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)
    }
  }); 
});
Run Code Online (Sandbox Code Playgroud)

茉莉花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)
    }
  }); 
});
Run Code Online (Sandbox Code Playgroud)