Search code examples
javascriptruby-on-railstestingtddjasmine

Jasmine specs generating different random numbers than on execution


I have a Jasmine test that is failing because a random number is being generated and this random value is different for execution and spec.

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

The test below fails because Math.floor(Math.random()*10000) is generating different values.

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

Is there a way to make my test pass for cases where I have random numbers being generated?


Solution

  • You're able to mock Math.random function. Jasmine 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)
        }
      }); 
    });
    

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