How to expose javascript objects for unit testing without polluting the global namespace

I have a javascript autocomplete plugin that uses the following classes (written in coffeescript): Query, Suggestion, SuggestionCollection and Autocomplete. Each of these classes has an associated specification written in Jasmine.

The plugin is defined inside the module, for example:

(function(){ // plugin... }).call(this); 

This prevents classes from being polluted by the global namespace, but also hides them from any tests (specs with jasmine or unit tests with something like q-unit).

What is the best way to expose javascript classes or objects for testing without polluting the global namespace?

I will answer the solution I came up with, but I hope there is something more standard.

Update: my attempted solution

Because I am new to <100 xp, I cannot answer my question within 8 hours. Instead of waiting, I just add what I did here.

To specify these classes, I invented a global object called _test , which I showed to all classes for testing. For example, in coffeescript:

 class Query // ... class Suggestion // ... // Use the classes // Expose the classes for testing window._test = { Query: Query Suggestion: Suggestion } 

In my specs, I can show the class that I'm testing:

 Query = window._test.Query describe 'Query', -> // ... 

The advantage is that only the _test object _test dirty, and it is unlikely that it will encounter another definition of this object. However, it is still not as clean as we would like. I hope someone will provide a better solution.

+7
source share
1 answer

I think something like the CommonJS module system (e.g. brunch ) will work.

You can split your code into modules, and the parts they need will import them through require . The only part that gets “dirty” is the module card, supported by the module control code, very similar to your test object.

In Autocomplete.coffee

 class exports.Query // ... class exports.Suggestion // ... 

and then at Autocomplete.spec.coffee

 {Query, Suggestion} = require 'app/models/Autocomplete' describe 'Query', -> 
+3
source

All Articles