35

Is their any way to have multiple parameters in one test instead of copying and pasting the function again?

Example in NUnit for C#:

[TestCase("0", 1)]
[TestCase("1", 1)]
[TestCase("2", 1)]
public void UnitTestName(string input, int expected)
{
    //Arrange

    //Act

    //Assert
}

What I want in Js:

describe("<Foo />", () => {

    [TestCase("false")]
    [TestCase("true")]
    it("option: enableRemoveControls renders remove controls", (enableRemoveControls) =>  {
        mockFoo.enableRemoveControls = enableRemoveControls;

        //Assert that the option has rendered or not rendered the html
    });
});
Martin Dawson
  • 7,455
  • 6
  • 49
  • 92
  • Just make a new function and call it, I guess. In general, since you are passing a callback to `it` (and `describe`, etc) you can just make a function that returns a callback `function makeTest(input, expected) { return function() { assert(input === expected)})` then just call it in your tests `it("passes", makeTest(1, 1))` and vary the arguments `it("fails", makeTest("apple", "orange"))` – VLAZ Oct 26 '16 at 22:14

3 Answers3

65

An alternative is to use Jest. It has this functionality built-in:

test.each`
  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
  ${2} | ${1} | ${3}
`('returns $expected when $a is added $b', ({a, b, expected}) => {
  expect(a + b).toBe(expected);
});
Chris
  • 6,914
  • 5
  • 54
  • 80
Asen Arizanov
  • 930
  • 1
  • 9
  • 11
15

You can put the it-call inside a function and call it with different parameters:

describe("<Foo />", () => {

    function run(enableRemoveControls){
        it("option: enableRemoveControls renders remove controls", () =>  {
            mockFoo.enableRemoveControls = enableRemoveControls;

            //Assert that the option has rendered or not rendered the html
        });
    }

    run(false);
    run(true);
});
Kenneth
  • 28,294
  • 6
  • 61
  • 84
3

If you're using Mocha you can combine it with mocha-testdata:

import * as assert from assert;
import { given } from mocha-testdata;

describe('<Foo />', function () {
    given([
        { input: true,  expected: 'some expected value',       description: 'flag enabled' },
        { input: false, expected: 'some other expected value', description: 'flag disabled' },
    ]).
    it('option: enableRemoveControls renders remove controls', function ({ input, expected }) {
        // prepare, act, assert
    });
});

In the above sample you'll also notice a description field that's not being injected into the test. This little trick can be used to make the reported test name more meaningful.

Hope this helps!

Jan

Jan Molak
  • 4,426
  • 2
  • 36
  • 32