jeudi 23 septembre 2021

Best practices on reusing test inputs in JavaScript

I've written a fixed-point math library, which comes in two flavors: the signed and the unsigned flavor.

The tests across the two flavors have lots of inputs in common. E.g. for the avg function:

// Signed tests inputs
context("when one operand is zero and the other is not zero", function () {
  const testSets = [
    [fp("-4"), fp("0")],
    [fp("0"), fp("-4")],
    [fp("0"), fp("4")],
    [fp("4"), fp("0")],
  ];
  // ...
});


// Unsigned tests inputs
context("when one operand is zero and the other is not zero", function () {
  const testSets = [
    [fp("0"), fp("4")],
    [fp("4"), fp("0")],
  ];
  // ...
});

The values in the testSets arrays are duplicated. Links to GitHub:

The question is, how to refactor my code base such that I don't repeat myself? Is there a "best practice" for this scenario? I read about snapshot testing, though that doesn't tackle test inputs. I said that maybe I should fake the data. But I'm not sure that makes sense in my case, because the inputs for my mathematical functions are bound by a domain.

Note: I am running my tests with Mocha.

Aucun commentaire:

Enregistrer un commentaire