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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With