JQuery Mobile
JQuery Mobile

Reputation: 6301

Generating Tests in Jasmine

I have some JavaScript that I am testing with Jasmine. At this time, one of my suites look like this:

var library = require('../library');

describe('My App -', function() {
   afterEach(function(done) {
      // some clean up code goes here
      library.cleanUp(done);
      done();       
   });

   describe('Test Operation 1 -', function() {
      beforeEach(function(done) {
         library.init(done);
      });

      it('should load fine', function() {
        if (library) {
          expect(true).toBe(true);
        } else {
          expect(false).toBe(true);
        }
      });

      var parameters = [1, 8.24, -1];
      var results = [5, 4, 0];

      // [TODO]: Create tests here
   });   
});

Is there a way for me generate specs from my parameters and results arrays? In other words, at runtime, I would essentially like to dynamically run:

it('should be 5 when parameter is 1', function(done)) {
  var result = library.calculate(1);
  expect(result).toBe(5);
  done();
});

it('should be 4 when parameter is 8.24', function(done) {
  var result = library.calculate(8.24);
  expect(result).toBe(4);
  done();
});

it('should be 0 when parameter is -1', function(done) {
  var result = library.calculate(-1);
  expect(result).toBe(0);
  done();
});

I do NOT want the following:

it('should test the parameters', function() {
  for (var i=0; i<parameters.length; i++) {
    var result = library.calculate(parameters[i]);
    expect(results[i]).toBe(result);
  }
});

I am trying to figure out how to dynamically generate some tests at runtime.

Thank you!

Upvotes: 2

Views: 3683

Answers (1)

kbgn
kbgn

Reputation: 856

Based on @Michael Radionov's comment you can dynamically generate test cases using a for loop.Sample code for dynamic test case generation is provided below:

describe("Generating Tests with Jasmine",function(){
        //var parameters = [1, 8.24, -1];
        //var results = [5, 4, 0];

        var tests = [
            {parameter: 1,       result: 5},
            {parameter: 8.24,    result: 4},
            {parameter: -1, result: 0}
        ];

        tests.forEach(function(test) {
            it('should be ' + test.result + ' when parameter is '+test.parameter, function(done) {
                var result = library.calculate(test.parameter);
                expect(result).toBe(test.result);
                done();
            });
        });

    });

Upvotes: 12

Related Questions