Unit test template with required RequireJS modules

Let's say I have a RequireJS module and there is only one instance in my application (let's say it does something asynchronous and has callbacks):

// modules/myModule define(function(){ var module = function(){ var self = this; self.runSomething(){ console.log("hello world"); }; }; return new module(); }); 

and I want a unit test instance of this module, I found that I am creating the module as follows:

 // modules/myModule define(function(){ return function(){ var self = this; self.runRouting(){ console.log("hello world"); }; }; }); // modules/myModuleInstance define(["modules/myModule"], function(myModule){ return new myModule(); }); 

This gives me something that is not attached to the state, which I can then tap out of my unit tests, so in my unit tests I never refer to modules/myModuleInstance , only the modules/myModule that I create for each test every time. The application then references modules/myModuleInstance .

It looks like an anti-pattern. I hate having the extra part of a β€œmodule instance”. I know about setup and deletion methods in unit tests and I can support this instance this way, but seeing what can happen with C # when trying to unit test massive singlets, messing with the state between unit tests is what I really I want to avoid, especially with a dynamic language.

What do people usually do in this case?

+6
source share
1 answer

After Luke McGregor commented on this, it was obvious that what I had in the first code snippet was wonderful. Using testr.js I can define a module that runs tests as follows:

 // tests/myModuleTests define(["modules/myModule"], function(myModule){ var instanceOfModule = testr(myModule); // run some tests var anotherInstanceOfModule = testr(myModule); // run some other tests }); 
0
source

Source: https://habr.com/ru/post/954462/


All Articles