Testing example

For the Calculator app example, let's create the src folder in the root project's folder and create the calculator.js file inside:

$ mkdir src
$ touch src/calculator.js

As you can see, we are not saving our calculator.js file inside the specs/ folder, so we need to configure karma to load the files present in the src/ folder. Apply the following changes in the karma.conf.js file:

...
files: [
'specs/*.spec.js',
'src/*.js'
],
...

Now, Karma will load all the files from the specs and src folder when testing is running.

Let's implement the code of our calculator.js file. Using your editor of choice, open the src/calculator.js file and apply the following code:

window.Calculator = {

add: function(n1, n2) {
return n1 + n2;
},

multiply: function(n1, n2) {
return n1 * n2;
}

}
If you want to make a variable accessible globally, simply create it as a property of the window object. In this case, we made the Calculator object global.

Now, let's write our test case. Open the specs/calculator.spec.js file and apply the following code:

describe("Calculator Tests", function() {

it("should return 10", function() {

expect(window.Calculator.add(5, 5)).toBe(10);

});

});

The preceding code should be familiar to you if you note that we are using the Jasmine testing framework to write our tests. Now that we have everything set up and our code implemented, let's continue by launching the tests.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset