DEV Community

Zach
Zach

Posted on • Originally published at zach.sexy

2

Parameterized testing in Deno

I'd like to share a simple function I wrote for parameterized test in Deno.

One of the things I like about Deno is that the developers are building in a lot of boilerplate tooling into the runtime. This reduces a lot of the code that seems to come along by default with node projects. A mid-sized node project can easily have a dozen or so primary dependencies supporting testing, and many more transitive dependencies.

Deno, on the other hand, only has one function related to testing in the runtime api (Deno.test, to register tests), and a small handful of assertions in the standard library. It's all you really need, but sometimes the extras can be nice.

Like parameterized tests. If you haven't used a test library that supports them, parameterized tests are basically just a syntactic sugar for running the same test case on different inputs. For example, Jest's .each function.

To achieve something similar in Deno, give this a try (I called it 'each' as well, for lack of a better name):

function each<T>(params: Record<string, T>, cb: (p: T) => void) {
  Object.keys(params).map(title => {
    Deno.test(title, () => { cb(params[title]) });
  });
}

Enter fullscreen mode Exit fullscreen mode

Calling it looks like this:

import { assertEquals } from "https://deno.land/std@0.107.0/testing/asserts.ts";
each<[number[], number]>(
  {
    "1 + 2 + 3 == 6":     [[1, 2, 3], 6],
    "-1 + -2 + -3 == -6": [[-1, -2, -3], -6],
    "1 + 1 == 2":         [[1, 1], 2],
    "10 + 9 + 8 + 7 == ": [[10, 9, 8, 7], 34],
  },
  ([vals, expected]) => {
    const actual = vals.reduce((a,b) => a + b);
    assertEquals(expected, actual);
  }
);
Enter fullscreen mode Exit fullscreen mode

Hopefully this can be helpful to someone, at least until more comprehensive testing features are added to the Deno runtime. You can read some of the ongoing discussion around a new test related api here.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
canrau profile image
Can Rau

Interesting, thanks for sharing 🙏

I just use a for..of loop so far like so

for (const test of testCases) {
    assertEquals(await functionToTest(test.arg, test.arg2), test.result);
}
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more