To run JavaScript Unit tests using the Jasmine Testing framework, install Jasmine as a Node plugin. Once installed it can also be incorporated as part of your build process and run as a task on each build. One can also download Jasmine directly and install it, rather than use NPM. Doing so as a standalone comes with it a html page SpecRunner.html. This html file loads the testing framework, the javascript files that need to be tested and executes the tests.
By convention, for your test files create a "spec" folder and name your test files like test1.spec.js where test1 can be any appropriate name for your test.
Use the snippet of a unit test specification to create the specs. Note the use of nested describe functions to group a set of unit tests.
describe("Expect", function(){ // Jasmine executes this function when the tests run
describe("false", function(){
it("to be equal to false", function(){
expect(false).toEqual(false); // expect function is the assert method
});
});
// Add other describe functions here like the spyOn test below
});
Jasmine interprets this spec as "Expect false to be equal to false" and give it this test name. The string "Expect" will be prepended to any tests within the group. The it function describes an actual test within the group. This function also takes 2 parameters just like the describe function.
We can also use the spyOn function to test(spy) if a function has been called, how many times it has been called and with what parameters.
describe("my coolFunction", function(){
it("is called", function(){
// create object wrapper around the function expected to be called
var thisIs = {
coolFunction : function (){}
}
spyOn(thisIs, "coolFunction");
thisIs.coolFunction(); //call the function
expect(thisIs.coolFunction).toHaveBeenCalled();
});
});
});
Instead of calling the actual method, we should actually create and use a mock of the function as all we are interested in knowing is whether the function has been called or not.
No comments:
Post a Comment