JS单元测试使用不同的参数多次运行

Mar*_*son 5 javascript mocha.js reactjs enzyme

他们有什么办法可以在一个测试中拥有多个参数,而不是再次复制和粘贴函数吗?

NUnit中用于C#的示例:

[TestCase("0", 1)]
[TestCase("1", 1)]
[TestCase("2", 1)]
public void UnitTestName(string input, int expected)
{
    //Arrange

    //Act

    //Assert
}
Run Code Online (Sandbox Code Playgroud)

我想要的Js:

describe("<Foo />", () => {

    [TestCase("false")]
    [TestCase("true")]
    it("option: enableRemoveControls renders remove controls", (enableRemoveControls) =>  {
        mockFoo.enableRemoveControls = enableRemoveControls;

        //Assert that the option has rendered or not rendered the html
    });
});
Run Code Online (Sandbox Code Playgroud)

Ken*_*eth 11

您可以将it-call 放在函数中并使用不同的参数调用它:

describe("<Foo />", () => {

    function run(enableRemoveControls){
        it("option: enableRemoveControls renders remove controls", () =>  {
            mockFoo.enableRemoveControls = enableRemoveControls;

            //Assert that the option has rendered or not rendered the html
        });
    }

    run(false);
    run(true);
});
Run Code Online (Sandbox Code Playgroud)


小智 10

另一种方法是使用Jest。它具有内置的此功能

test.each`
  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
  ${2} | ${1} | ${3}
`('returns $expected when $a is added $b', ({a, b, expected}) => {
  expect(a + b).toBe(expected);
});
Run Code Online (Sandbox Code Playgroud)