2

I am testing a function which returns an object. Value of one of its key is current time in miliseconds. How can we test it using jasmine?

var fun = function(name,id){
    var obj = {
        name : name,
        id : id,
        createdTime : Date.now()
    }
    return obj;
}

expect(fun("abc",1)).toBe({name:"abc",id:1,createdTime:Date.now()})

Date.now() returns 2 different values because main function & test case both runs at different time.

Vish
  • 139
  • 2
  • 11

1 Answers1

1

Depending on how specific you need it to be, you could create a range of +-1 second or some similar number with toBeWithinRange from the Jasmine Matchers package:

expect(createdTime).toBeWithinRange(Date.now() - 1000, Date.now() + 1000)

With this method you will have to test the createdTime separately from the other test, but that shouldn't be too big of an issue. You just need to assign the return property that you want to the variable createdTime.

Edit- A similar method with a more clear matcher is using toBeNear:

expect(createdTime).toBeNear(Date.now(), 2);

This will be true if the date assigned to createdTime is within two seconds of the date when the test runs.

Edit 2- to exclude object keys when testing, you can follow an example here. This is how you would do it in your case:

var joc = jasmine.objectContaining;
expect(fun("abc",1))
.toEqual(joc({
    name:"abc",
    id:1
}));
Aaron Meese
  • 1,670
  • 3
  • 22
  • 32