Skip to content
Advertisement

How to mock libraries that are unknown in Javascript on my local environment?

I am developing a website using Javascript for a device which has a particular Javascript library that can be used. This Javascript library is known on the device but it is not known locally. F.e. I execute library.function(). For this, locally I get the error: library is not defined.

Is there a way to avoid this error locally so that I can test those parts without commenting it out? To mock the libraries that are unknown locally.

Advertisement

Answer

Is this a global scoped library? If yes, you can substitute it and mock the behaviour:

var MockLib = {
   someFunction: () => console.log("someFunction called"),
   someOtherFunc: (args) => console.log("someOtherFunc called", args),
   someProp: "value-123",
};

window.library = window.library || MockLib;

Then, executing library.someFunction() will execute the function on the library if it was already defined or your mock if not.

Just make sure to put the window.library assignment AFTER the library should have been loaded.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement