Karma among with Jasmine, RequireJS and PhantomJS

This time something about JavaScript. Everybody likes JavaScript :P.

I’d like to write quick guide how to set up working tests environment.

First, what we need:

Let get all required things by NPM. Create a package.json with content:

Now run the command:

Great. We have now all required dependencies.

Next thing is to configure Karma. There are two ways of doing this, manually by creating a karma config file or using karma creator (karma init command). I prefer doing it manually. Create a new file and name it karma.conf.js. Here’s my file with comments:

Basically what you need to change is basePath and files / exclude. But that’s not all. We need to create another file which will run asynchronous our test with RequireJS. Let’s place this file in the tests and name it main.js. This is the only file which is included by karma. Content of the file:

Variable window.__karma__.files comes from karma.conf.js files section. We need to filter them as we want to require only tests files. The source files will be declared as dependencies of each test file.

Let’s create a example test file tests/exampleSpec.js and put in it:

We are defining a spec which has source file as a dependency. RequireJS injects it’s to our spec and we can now test it with Jasmine. How cool is that?

Let’s define our example via src/example.js:

The last thing which need to be done is to export the variable which will tell Karma where PhantomJS binary is:

Now let’s run Karma:

Finally you should see something like this:

karma

If you have any problems with PhantomJS – maybe you need to install some libs required by it. Check it’s website for more info. Other solution is to try different browser – Chrome, Firefox etc. But this can’t be done via SSH… 🙂

Any problems, suggestions, feel free to comment.

 

3 przemyślenia nt. „Karma among with Jasmine, RequireJS and PhantomJS”

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *