Jasmine in Action
Let's explore how we can write tests in Jasmine with the help of an example.
Running Jasmine test
The first thing we need to do is have an example piece of code to test.
Say we have a function that returns the name of the book in the browser. This function would look like this:
function writeTitle() {
return 'Getting Started With Angular';
}
A very simple function, but it will allow us to write a simple test. The test will look like this:
describe('writeTitle function', () => {
it('returns Getting Started With Angular', () => {
expect(writeTitle()).toEqual(
'Getting Started With Angular'
);
});
});
So, this is our first test. It is a very simple example, but it does have a lot going on. There are a number of features of the Jasmine framework being used in this example. Let’s take a minute to explore what these features are.
📝 Note: Press the RUN button to run the test given below.
/* The "exports" keyword is used to ensure that the functionality defined in this file can actually be accessed by other files.*/ var exports = module.exports={}; // Make function public so other modules can access it exports.writeTitle = function() { return 'Getting Started With Angular'; }
You should see the following in the output:
1 spec, 0 failures
Finished in 0.009 seconds
As you can see from the output, there is 1 test spec and 0 failures. If there was a failing test, the output would show it.
📝 Note: Try changing ...
Get hands-on with 1400+ tech skills courses.