Karma is one of the most commonly used tools for test execution; it is compatible with many testing frameworks (such as Mocha, QUnit, and Jasmine). You can use it to test any JavaScript code, and it is highly recommended that you use some tool to test and perform automated testing on SPA.
In the following examples, we will be using Jasmine to write the tests and Karma to run the test. Jasmine has a very simple and easy writing syntax. Also, it is not dependent on any other framework. A basic example of writing tests looks like the following code:
describe("The test name", function() { it("contains spec with an expectation", function() { expect(true).toBe(true); }); });
describe()
and it()
are two functions. The describe()
function has two parameters: a string parameter that receives the name of the test, and a function
parameter that implements the spec using the it()
function. The expect()
function is a matcher function to get a result. The matcher function receives a boolean
value comparison between the actual value and the expected value. Here is a simple example to understand matcher with an expect()
function:
describe("How matchers works:", function() { it("The 'toBe' matcher compares with ===", function() { var number = 12; var letter = a; expect(number).toBe(letter); expect(number).not.toBe(null); }); });
Matcher is very useful; we can create our own matcher if necessary.
We can use the describe()
function to group related specs to test an entire module like the following example:
describe("Login test series", function() { it("Try to login with blank user", function() { ... }); it("Try to login with wrong user", function() { ... }); // More it() functions goes here. });
The Jasmine API is pretty easy to understand; it has several other functions, but this baseline is enough to understand the following examples.
To find out more about the Jasmine test framework, refer to http://jasmine.github.io/.
Let's take a look at the Karma test runner and how to start using it.
18.220.124.177