JS Unit Testing: Expected on Callback

I use a Leaflet and I create a marker on it. Once the mouse exited this marker, I would like to remove the popup that I show on the mouseenter :

 marker.on('mouseout', e => this.leafletMap.closePopup()); 

In my testing, I would like to know if there is a callback that I expect.

I am already testing if an event occurs when the mouse is displayed with

 expect((mockedMarker.on as jasmine.Spy).calls.argsFor(0)[0]).toEqual('mouseover'); 

Any ideas on how to do this?

I tried something like this

 expect((mockedMarker.on as jasmine.Spy).calls.argsFor(0)[1]).toEqual(JSON.stringify(component.leafletMap.closePopup)); 

But I don’t know what I am doing (I am new to unit testing) and I can’t find a solution on the Internet because I really don’t know what to call this test.

I must indicate that I am working in Typescript .

+7
unit-testing angular typescript jasmine leaflet
source share
2 answers

It seems that you want to verify that the callback function does what you want. To do this, you should not check the function line. This test will be too fragile.

Instead, you should verify that the callback closes when the callback is called. Here is a simple test for this. It assumes that you have secured the marker, brochure, and callback correctly:

 describe('Marker', () => { it('should invoke closePopup', () => { let marker = createMarkerWithLeaflet(); spyOn(marker, 'on'); spyOn(marker.leaflet, 'closePopup'); marker.on.calls.argsFor(0)[1](); expect(marker.leaflet.closePopup).toHaveBeenCalled(); }); }); 
0
source share

What you do is not a unit test, but since you want to test, I would give a solution. Below is a sample jasmine script that I developed for you.

 let marker = function() { function on(a, b) { console.log(a, b); } this.on = on; } describe('this', () => { it('xya', () => { y = new marker() spyOn(y, 'on'); y.on('onmouseout', e => this.leafletMap.closePopup()); const lambda = y.on.calls.argsFor(0)[1] console.log(lambda.toString()) expect(lambda.toString()).toEqual("e => this.leafletMap.closePopup()") }) }) 

Work on the terminal

 $ npx jasmine mocking.js Randomized with seed 33786 Started e => this.leafletMap.closePopup() . 1 spec, 0 failures Finished in 0.006 seconds Randomized with seed 33786 (jasmine --random=true --seed=33786) 
+1
source share

All Articles