Introduction to Jasmine and Karma

This time I’ll say a few words about testing. Jasmine is a testing framework for JavaScript, quite similar to unit tests in C#. Its main feature is that syntax resembles natural language and the testing methods don’t have descriptive names, but they are passed together with their descriptions as parameters to the framework’s functions instead. There are simple examples in the official guide. Jasmine is supposedly provided together with an HTML runner. I’m not sure if it’s still valid because there are rather few references to it and after I’ve seen this config I fully understand why people prefer Karma. This is a test runner with a debug mode, in which one can add breakpoints and execute code in a console during test runtime, just like in normal application runtime.


Unfortunately, there are some issues as well. First, there are different packages required depending on a browser. There is something wrong with the one for Opera – the launcher keeps opening 3 instances of the browser, stating that it failed twice. Second, in Firefox there is a distracting stack trace right below tests which failed, which doesn’t point well to a place in my code:

Karma Firefox Opera

Karma requires some configuration in an extra file, but unfortunately I won’t elaborate on it here. I just copied that config from the official Angular 2 application template, replaced Chrome (which I don’t have) with Firefox/Opera and adjusted paths. What was confusing to me was the fact that Karma seems to launch browsers with default settings, so for example my custom keyboard shortcut for displaying Dev Tools didn’t work. Just like the TypeScript compiler, Karma offers a watch mode – when a source file changes, it reruns its task. Currently there isn’t much to test, but I’ve made a temporary stub service for getting categories – there is no database nor server at all yet, so when I add it and update the service, a test will be beneficial.
In the context of Angular, the above refers to testing ‘pure’ classes. However, it’s also possible to test components – we can manipulate them and check whether a template reacts correctly. Seems cool, but I’ll rather skip it for now, because there are some higher priorities.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s