57

Okay as a C# NUnit guy this might be odd.

But does jasmine allow parameterized unit test?

I am not sure if it goes against the "declare" and "it" to make things readable to non programmers.

I have seen some third party plug ins but they are kind of old, not sure if it has been added to jasmine. If I am ment to use a plug in

Just to help anyone who finds this in the future, I have been told on jasmine forum There is no first class support for parameterized tests within Jasmine itself.

1
  • 1
    You could post the answer you found on the Jasmine forum as an answer to your own question and accept it.
    – TrueWill
    Commented Aug 3, 2016 at 18:07

5 Answers 5

51

Based on piotrek's answer and the article Parameterized testing in Javascript, you could also use the following approach which uses ES6 syntax:

[
  ['abc', 3],
  ['ab', 2],
  ['', 0],
].forEach(([string, expectedLength]) => {
  it(`should return length ${expectedLength} for string "${string}"`, () => {
    expect(string.length).toBe(expectedLength);
  });
});

I have tested it with the Jest test framework, but it should work with Jasmine as well.

1
  • It ought to be added that if you have a beforeEach block and possibly an afterEach block this entirely breaks. If you try and set up a test this way with a beforeEach block Jest throws a 'TypeError: Cannot read property '[object Array]' of undefined' exception. However all is not lost, it seems to work if you assign the test cases to a variable and iterate over that, as per Dymtro's answer stackoverflow.com/a/55909737/1392407
    – Astridax
    Commented Jul 12, 2019 at 16:03
51

Better solution (especially if you use TypeScript)

Another solution is to use Array of Objects instead of Array of Arrays. It fits better if you use some typing system like TypeScript.


Type issue

Imagine you have the following parametrised test:

it('action(value) should reset the forms pool only if value is true', () => {
  [
    [true, 1],
    [false, 0],
  ].forEach(([value, calledTimes]) => {
    spyResetFormsPool.calls.reset();

    component.action(value); // type error #1

    expect(spyResetFormsPool).toHaveBeenCalledTimes(calledTimes); // type error #2
  });
});
    

with TypeScript, it will fail to compile giving two errors:

error #1:

error TS2345: Argument of type 'number | boolean' is not assignable to parameter of type 'boolean'.

error #2:

error TS2345: Argument of type 'number | boolean' is not assignable to parameter of type 'number'. Type 'true' is not assignable to type 'number'.

That is because TypeScript sees an array of 'number | boolean'.

We could quickly solve this warning by using some explicit cast:

it('action(value) should reset the forms pool only if value is true', () => {
  [
    [true, 1],
    [false, 0],
  ].forEach(([value, calledTimes]) => {
    spyResetFormsPool.calls.reset();

    component.action(value as boolean); // necessary cast

    expect(spyResetFormsPool).toHaveBeenCalledTimes(calledTimes as number);  // necessary cast
  });
});

however this solution is not very nice.


Solution

A better way is to use Array of Objects, so the types are correctly handled by default and there is no need of explicit casting:

it('action(value) should reset the forms pool only if value is true', () => {
  [
    { value: true, calledTimes: 1 },
    { value: false, calledTimes: 0 },
  ].forEach(({ value, calledTimes }) => {
    spyResetFormsPool.calls.reset();

    component.action(value);

    expect(spyResetFormsPool).toHaveBeenCalledTimes(calledTimes);
  });
});

Do you want to use for instead of forEach (I personally find it more readable)? That's also possible:

it('action(value) should reset the forms pool only if value is true', () => {
  for (const {value, calledTimes} of [
    {value: true, calledTimes: 1},
    {value: false, calledTimes: 0},
  ]) {
    spyResetFormsPool.calls.reset();

    component.action(value);

    expect(spyResetFormsPool).toHaveBeenCalledTimes(calledTimes);
  }
});

Alternatively, you can also move the it inside the loop. When I do this, I usually add a testId to each object so I can keep track of which tests are failing:

for (const {value, calledTimes} of [
  { testId: 1, value: true,  calledTimes: 1 },
  { testId: 2, value: false, calledTimes: 0 },
]) {
  it(`action(value) should reset the forms pool only if value is true [${testId}]`, () => {
    spyResetFormsPool.calls.reset();

    component.action(value);

    expect(spyResetFormsPool).toHaveBeenCalledTimes(calledTimes);
  });
}
1
  • This doesn't print out the actual values in the test name.
    – Jim
    Commented Jan 11 at 15:38
17

You can use the following convention to increase readability:

const testCases = [
    {actualValue: true, expectedValue: true},
    {actualValue: false, expectedValue: false}
]

testCases.forEach(({actualValue, expectedValue}) => {
    it(`should be the same given: ${actualValue} and expected :${expectedValue} values`, () => {
      expect(actualValue).toBe(expectedValue)
    })
})

You'll see the following test cases to run:

Test Results
+ should be the same given: true and expected: true values
+ should be the same given: false and expected: false values
5

i haven't worked with jasmine since a long time but it was pretty easy to add parameterized tests:

  ['abc', 3,
   'ab',  4,
   '',    0].
it('should contain string length', function(string, expected){
   expect(string.length).toBe(expected);
});

with just a few lines of infrastructure code:

Array.prototype.it = function(description, testCaseFunction) {
     _(this)
      .chunk(testCaseFunction.length)
      .each(function(innerArray){
                it(description + ' ' + JSON.stringify(innerArray), function(){
                   testCaseFunction.apply(this, innerArray);
                });     
      })
      .value();
};

depending on your desired syntax and willingness to change default js objects, you have plenty of options: http://blog.piotrturski.net/2015/04/jasmine-parameterized-tests.html

1

So I started combining:

  • YAML using js-yaml
  • jasminejs
  • Typescript

to create what I believe are readable parameterized tests like this:

import YamlTableReader, {fixtureData, TestData} from "./YamlTableReader";    

describe("TestSuite", () => {
        describe("Real TestCase with Data Fixture", () => {

            // now using tagged template-string to auto convert into YamlTableReader. 

            var testdata = fixtureData ` 

            |   ID  | Value1 | Value2 | Squared |
            |   0   |1       | 1      | 1       |
            |   1   |2       | 2      | 4       |
            |   2   |3       | 3      | 91       |

            `;
            // This actually creates a test for each row of the table above
            testdata.describeEach("Square Test","[ID={ID}]:{Value1} x {Value2} should be equal to {Squared}",
                (row: {Value1: number, Value2: number, Squared: number}) => {
                    expect((row.Value1 * row.Value2)).toBe(row.Squared)
                }
            );
        });

Running this will give the following results:

Failures:
1) TestSuite 2 Real TestCase with Data Fixture Square Test : [ID=2]:3 x 3 should be equal to 91
  Message:
    Expected 9 to be 91.

Sources: https://github.com/deicongmbh/jasmine-param-tests

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.