williamsandonz
williamsandonz

Reputation: 16430

How to ensure DRY code in Jasmine Unit tests?

If I have a popover say, and I want to test it:

  1. being created
  2. being manipulated
  3. being destroyed

It is beneficial to have it declared in one place (tucked inside "describe"), so that it can be shared across the "its".

Should one share things between tests? I.E test2 relies on test1 being run first? What is the best way to do this with Jasmine?

Upvotes: 1

Views: 221

Answers (1)

Yaroslav Yakovlev
Yaroslav Yakovlev

Reputation: 6483

It`s a bad thing to rely to test order. To share things between tests you can have a way to set state of an object. Assume the pseudo code below:

var popover = getPopover({state:'init'});
//checking init state
...
//other test starting
var popover = getPopover({state:'manipulated'});
//checking the state

So the main idea is to be able to init your object at the state you need. Note, that if it's not much code to perform initialization and you are not going to need to reuse it much, you can hardcode the state setup for every test. Sure, it's not dry, but you benefit from tests that can be read, without references to other methods. Sometime it's a good thing, but it depends.

Also, you can use beforeEach and afterEach for setup and teardown before and after every test( it's a describe level thing ). Which is one of the preferred ways to perform state initialization and cleanup.

Upvotes: 1

Related Questions