Migrating from Jasmine 1.3 to Jasmine 2.0

If you just started a new JavaScript project with Jasmine, you likely started using Jasmine 2. But if you’re working on an existing project, it’s highly possible you’re using Jasmine 1.3 and maybe want, like me, migrate to Jasmine 2. Here are a few tips how to do it.

Spies
The way spies are used has slightly changed in Jasmine 2.

becomes:

Async tests
In Jasmine 1.3, if you wanted to test methods that are asynchronous, you had to use a lach coupled with waitFor and runs. Otherwise your test wouldn’t wait for the async call to return and could break into another test, with no direct relation. You could for example have something like this:

Jasmine 2.0 opted for a new async syntax that is similar to Mocha, and much easier to use than the older method. You don’t have to add to call any runs() or waitFor() functions. The only thing you have to do is to use the extra done parameter that is now available to beforeEach(), it() and afterEach(). The above code could be written like this:

As you can see it’s way more simple and straightforward. Note that test will fail if done method isn’t called before jasmine.getEnv().defaultTimeoutInterval.

new Clock

becomes:

using karma-jasmine-html-reporter with AngularJS
If you are using Jasmine with AngularJS to test directives, you may have an helper file that gets loaded by Karma with the following code:

The problem is that this will empty the whole body of your page before running each test, and as a result it breaks the jasmine-html reporter. In order to fix this you may change the above line to something like:

This isn’t optimized at all, but at least it doesn’t break the plugin anymore.

I think that the new async stuff is enough to migrate to Jasmine 2 if you are still using Jasmine 1.3. And as you can see, migrating isn’t that complicated so there’s no reason to stick with an outdated Jasmine 1.3.


Warpdesign.fr