Building and Testing
Anatomy of a Jasmine test
Jasmine announces itself as the "behavior-driven development framework for
testing JavaScript code". The behavior-driven testing roots are reflected in the
syntax employed by the library tests specifications that are supposed to read as
English sentences. Let's examine a simple test exercising a standard JavaScript
class to see how it works in practice:
describe('hello World test', function () {
var greeter;
beforeEach(function () {
greeter = new Greeter();
});
it('should say hello to the World', function () {
expect(greeter.say('World')).toEqual('Hello, World!');
});
});
There are several constructs in the above tests that need a word of explanation:
- The describe function, describes a feature of an application. It acts as an
aggregating container for individual tests. If you are familiar with other
testing frameworks you can think of the describe blocks as of test suites.
The describe blocks can be nested inside each other. - The test itself is located inside the it function. The idea is to exercise one
particular aspect of a feature in one test. A test has a name and a body.
Usually the first section of the test's body calls methods on an object under
test while the later one verifies expected results. - Code contained in the beforeEach block will get executed before each
individual test. This is a perfect place for any initialization logic that has to
be executed before each test. - The last things to mention are the expect and the toEqual functions. Using
those two constructs we can compare actual results with the expected ones.
Jasmine, as many other popular testing frameworks, comes with a rich set
of matchers, toBeTruthy, toBeDefined, toContain are just few examples
of what is available.