Ava: Provide a cleaner way to write parametric tests

Created on 26 Feb 2020  路  5Comments  路  Source: avajs/ava

Having a function like:

function sum(a, b) {
    return a + b;
}

I would like to create multiple tests with multiple combinations of a and b.

Currently, I can do so by "brute force":

function macroSum(t, a, b) {
    t.is(sum(a, b), a + b);
}
macroSum.title = (providedTitle = "", a, b) =>
    `${providedTitle}: ${a} + ${b}`

test(macroSum, 0, 0);
test(macroSum, 0, 1);
test(macroSum, 0, 2);
test(macroSum, 1, 0);
test(macroSum, 1, 1);
test(macroSum, 1, 2);
test(macroSum, 2, 0);
test(macroSum, 2, 1);
test(macroSum, 2, 2);

Or perhaps even better by using a for loop:

for (const params of [
  [1, 0],
  [1, 1],
]) {
  test(macroSum, ...params)
}

It would be great to have a simple/clearer way to write this.

In Python, with the pytest framework, I can do:

@pytest.mark.parametrize('a', [0, 1, 2])
@pytest.mark.parametrize('b', [0, 1, 2])
def test_sum(a, b):
    assert sum(a, b) == a + b

I think it is a great example. Note how I can define a list of possible values for each variable and how the name of the variable is assigned to the expected parameter in the test. The combinations are handled by the framework, so I do not need to create a list "by hand" to use in a for loop.

It also allows you to do something like (for other use cases):

@pytest.mark.parametrize('a,b', [[0, 0], [0, 1], [1, 0], [1, 1]])
def test_sum(a, b):
    assert sum(a, b) == a + b
question test-interface

All 5 comments

The for loop is about the best way you can do this currently.

I suppose something like test.parametrize() could take an array of parameters. I don't think that's worth including in AVA itself, at least at this stage. Perhaps somebody could publish a little package that wraps around AVA to provide this.

Let's leave this open for now for others to chime in.

But you have macros for that, just create a single macro and re-use it.
That will make much more clearer code and dubegability.

maybe someone ought write a recipe for that and slap it in the docs. py.test fans would eat that up :)

@novemberborn Has this been fixed? Or a recipe added to the docs? Or is the final resolution a "wont fix"?

Hey @Peque, per https://github.com/avajs/ava/issues/2414#issuecomment-593120059 I don't think we'll be adding this to AVA. Always open to link to examples or have a recipe, but IMHO it's not worth keeping this issue open for that.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fregante picture fregante  路  3Comments

carpasse picture carpasse  路  3Comments

niftylettuce picture niftylettuce  路  4Comments

electerious picture electerious  路  3Comments

avaly picture avaly  路  4Comments