简体   繁体   中英

How do I parameterize test cases in TypeScript unit tests?

I have a simple passing unit test:

describe("Example", () => {
    it("Return digits or empty string", () => {
        let actual = SmokeTest.ProblemOne("1");
        assert.equal(actual, "1");
    })
})

I now wish to test many other cases (empty string, more complex inputs and edge-cases). I have read about how to implement fixtures in TypeScript but this seems like overkill for an array of test-input, expected-output values.

What is the idiomatic way to define such an array in TypeScript / Mocha?

You can just make a function that you can reuse.

function assertProblemOne(input: string, expected: string): void {
    let actual = SmokeTest.ProblemOne(input);
    assert.equal(expected, actual);
}

describe("Example", () => {
    it("Return digits or empty string", () => {
        assertProblemOne("input here", "expected result here")
    })
})

However, I'm not sure that's really much better than simply.

assert.equal(SmokeTest.ProblemOne("1"), "1");

The only thing worse than debugging your code is debugging your tests. So unless there is a large amount of code that is shared between tests, I would recommend keep the code that runs in each tests as structurally simple as possible.

From the Mocha documentation :

No special syntax is required... to parameterize tests [you can] generate them with a closure.

describe("Example", () => {

    // define a closure that calls the method we are testing
    const testProblemOne = ({arg, expected}) =>
        function () {
            const actual = SmokeTest.ProblemOne(arg);
            assert.equal(actual, expected);
        }

    // invoke the closure for each test case
    it("Empty returns empty", testProblemOne({arg: "", expected: ""}));
    it("Single digit identity", testProblemOne({arg: "1", expected: "1"}));
    // additional test cases here...
})

This technique avoids using foreach in favor of readability and broader IDE integration.

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