Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with Jasmine, mocking a constructor

I'm unit testing JavaScript with Jasmine and I am running into some problems.

I have a large file to test and it has a lot of dependencies and those dependencies have their own dependencies. Because of said dependencies I want to mock all I can. There lies the problem. How can I mock a constructor so that it includes the methods that belong to it?

Lets say I'm testing a method createMap of class Map:

In that createMap method it calls for Layers class constructor using

var layers = new Layers()

I'm spying on it using

spyOn(window, 'Layers').and.callThrough()

That works fine but later in the createMap method it calls for layers.addLayer() where addLayer is a method of Layers class. Problem is that because I mocked the Layers call it doesn't recognize the addLayer method.

Is there a way to mock it so that it includes all the methods of the called class or is my only option to stub the whole Layers class or not mock it?

Or what would be a good way to handle this? I've tried to spyOn(Layers, 'addLayer') but there it says that no method addLayer is found.

I'm sorry if it's confusing a bit. I had trouble thinking how should I ask it.

like image 887
sergei Avatar asked Mar 16 '23 13:03

sergei


1 Answers

IMO, it's unnecessary to spy on window, since you can easily shadow the variable in local scope by creating a spy object with the same name:

describe('Map', function () {
    var Layers;

    beforeEach(function () {
        Layers = function () {
            // alternatively, you could move this to Layers.prototype
            this.addLayers = jasmine.createSpy('Layers#addLayers');
        };
    });

    /* ... */
});

If you want an automatic mocking and using CommonJS modules, you may try Jest framework, which is built on top of Jasmine.

like image 104
Pavlo Avatar answered Mar 26 '23 04:03

Pavlo