Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fake return calls from the geolocator in jasmine

I have a function that calls the geolocator and i don't know how to test this function. I've tried spying on the geolocator and returning fake data but with no success, the original function is still used and so i would have to wait and i couldn't use mock data.

// this doesn't work        
var navigator_spy = spyOn( navigator.geolocation, 'getCurrentPosition' ).andReturn( {
    coords : {
        latitude : 63,
        longitude : 143
    }
} );

How can I do this?

like image 794
Nicola Peluchetti Avatar asked Jun 19 '12 17:06

Nicola Peluchetti


1 Answers

Ah wait, maybe you HAVE to create the spy within your beforeEach block because Jasmine restores spies automatically after each test case. if you did something like:

var navigator_spy = spyOn( navigator.geolocation, 'getCurrentPosition' )

it("should stub the navigator", function() {
   // your test code
});

the spy is already restored when you want to test it. Use this instead:

beforeEach(function() {
    this.navigatorSpy = spyOn( navigator.geolocation, 'getCurrentPosition' )
});

it("should work now since the spy is created in beforeEach", function() {
    // test code
});
like image 149
DominikGuzei Avatar answered Oct 22 '22 14:10

DominikGuzei