Jasmine is a free JavaScript testing framework for BDD (Behavior Driven Development). In my opinion Unit-test should be written by developers, but tester you need also to know! This tutorial give you a hint how to use it.
Preparation
Download latest standalone version directly from GitHub and unzip. Now you have some files and folders. The file “SpecRunner.html” and “spec”, “src” folders are important for us. Some examples are allready included. If you run the “SpecRunner.html” in your browser, you can see the first example results. A look inside this examples help you understand Jasmine!
Short Introduction
In the “src” directory, are the things to be tested. The “spec” directory has the tests. The “SpecRunner.html” link to the all files. The comments describe what you should do. Whenever you want to run the tests, you simply need to load or reload.
Example
Delete all files into “src” and “spec” folders. Create on “src” folder a new file.
function say_hello(name) {
return "hello from " + name;
}
function simple_calc(value_a, value_b) {
return value_a + value_b;
}
function return_bool(value_a) {
return isNaN(value_a);
}
var timo = {human: "male"};
var john = {human: "male"};
And on “spec” folder this file.
describe("my first test suite", function() {
it("test for correct string", function() {
expect(say_hello("Lisa")).toContain("hello from Lisa");
});
it("test for correct value", function() {
expect(simple_calc(5, 6)).toEqual(11);
});
it("test for not a number", function() {
expect(return_bool("Hello")).toBeTruthy();
});
it("test for same object", function() {
expect(timo).toBe(john);
});
});
Now edit the “SpecRunner.html”. Just add the paths for JS files.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.3.4</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.3.4/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.3.4/jasmine.css">
<script src="lib/jasmine-2.3.4/jasmine.js"></script>
<script src="lib/jasmine-2.3.4/jasmine-html.js"></script>
<script src="lib/jasmine-2.3.4/boot.js"></script>
<!-- include source files here... -->
<script src="src/example.js"></script>
<!-- include spec files here... -->
<script src="spec/example.spec.js"></script>
</head>
<body></body>
</html>
That is it! 😉 Now your results shows 4 Specs with 1 failure.