Reputation: 721
I am new to unit testing with JavaScript and I am trying to test my code with Jasmine 2.3.4. I have written my application code (main.js) and put it inside a closure to avoid global variables, e.g.
main.js
(function(){
var baseURL = "https://google.co.uk";
// rest of application..
})();
Here is the testing code I am starting with:
mainSpec.js
describe('Document setup should set the base URI', function () {
it('Base URI', function () {
expect(baseURI).toEqual("https://google.com");
});
});
The problem I'm having is I don't know how to expose the code inside the anonymous function in main.js in such a way that it is available to be tested in mainSpec.js. What is the best approach for making my code in main.js accessible to my testing code? I'm not using Require or a module loader. Thanks.
Upvotes: 2
Views: 580
Reputation: 77
A simple approach would be using a temporary test variable. Variables INSIDE a closure are hidden from the outer world, but not the other way around
var test={};
(function(){
var baseURL = "https://google.co.uk";
// rest of application..
test.baseURL=baseURL;
})();
Describe('Document setup should set the base URI', function () {
it('Base URI', function () {
expect(test.baseURL).toEqual("https://google.com");
});});
Upvotes: 0
Reputation: 14429
You need to test this by mocking the things outside of your code that baseURI
uses. For example, maybe your code does a $.get(baseURI + '/something', ...);
Then you would go stub $.get
and expect it to have been called with a URI that starts with baseURI
.
If it is an option, using CommonJS makes testing much easier. You would be able to make a module say like this:
function MyClass(baseURI) {
this.baseURI = baseURI;
}
module.exports = MyClass;
MyClass.prototype.getURI() {
return this.baseURI;
}
...
Then you could test it by doing:
var MyClass = require('./myClass);
describe('MyClass', function() {
it('uses the set baseURI', function() {
var myClass = new MyClass('https://google.com');
expect(myClass.getBaseURI()).toEqual('https://google.com');
});
...
});
With most CommonJS tools, you can also mock or proxy the modules your module depends on (for example, with Browserify, I used proxyquireify). That way you can test how it interacts with your other modules. If you follow Single Responsibility Principle, that means your modules will generally stay smaller and change less often and are easier to test.
Upvotes: 1