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.

What you need to do is 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

Web Dev

Creating Docker images with M1 Macs

I ran into an issue with my Dockerfile when using it on a Linux machine, setting a platform fixed the issue

Web Dev

What does --no-owner mean in Postgres?

You have read a guide to doing Postgres exports or imports and seen --no-owner, this is what it means