简体   繁体   中英

How to create a data driven test in Node.js

In Node.js unit tests, what is the way to create data driven unit tests ?

For Example, I've a common function / method , which I want to re-use in multiple unit tests with different sets of data. I tried looking into nodeunit, vows, whiskey, qunit, expresso ; But I wasn't able to figure out a way to achieve this functionality.

I was not looking at calling the function literally in multiple tests, but rather use the common method in a loop to pick up the data in each iteration and execute it, as a unittest

The reason for this is, I've atleast 1000 rows of parameterized data, for which I want to write unittest . Obviously I cannot go on writing 1000 unittests physically.

Anyone could you please point me a way to achieve the above.

There is qunit addon which allows to run parameterized quint tests
https://github.com/AStepaniuk/qunit-parameterize

So you can separate test data and test method and run the same test method against different data sets.

This is a pretty old post, but I just hit this problem myself and wasn't able to find a clean solution for QUnit without using the plugin referenced by the other comment (qunit-parameterize). Honestly, I couldn't figure out how to integrate the plugin with my company's project and gave up after about an hour.

This is how I ended up solving it:

Just define an array with your inputs (and expected outputs, if needed), iterate over your array, and define the QUnit test in the callback! Super simple, really, but worked quite well.

const testCases = [
    { input: "01/01/2015", expected: "2015-01-01" },
    { input: "09/25/2015", expected: "2015-09-01" },
    { input: "12/31/2015", expected: "2015-12-01" }
];

testCases.forEach(testCase => {
    QUnit.test("gets first of month",
    () => {
        const actual = new classUnderTest().getFirstOfMonth(testCase.input);
        strictEqual(actual, testCase.expected);
    });
});

I wasn't sure that QUnit would discover the test if it were nested as such, but it does just fine.

Enjoy!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM