Using Loops in Jasmine

How to call tests numerous times when testing with Jasmine

If you want to test your code against 10 different inputs you don’t want to have to write 10 different tests. You want to write one test you can call 10 times.

The cleanest way to achieve this is to have your inputs and outputs stored in an array or object (In the example below I have chosen an array).

Intuitively (especially if you are familiar with how to write Rspec tests) it might feel like all you need to do is wrap your it block in a for loop and have your arrays feed into it, unfortunately due to the nature of how Jasmine executes this will not work.

Wrap your it block inside a function, which you can then call from inside a loop. For example;

describe('this is my looping test!', function() {
  var input = [1,2,3];
  var output = [10, 20, 30];

  function test_my_times_ten(input, output) {
    it('should multiply ' + input + ' by 10 to give ' + output, function() {
      expect(input * 10).toEqual(output)
    });
  }

  for(var x = 0; x < input.size; x++) {
    test_my_times_ten(input[x], output[x]);
  }
});

With this technique you can see how you could quickly build up a very large and comprehensive test suite without writing a large amount of tests, things start to get really interesting if you start having nested loops passing in input. Just be aware of the performance implications of nested loops though!

Recent posts View all

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.

VS Code Web Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code