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

mjqavswn  于 2023-02-22  发布在  React
关注(0)|答案(3)|浏览(269)

他们有没有办法在一次测试中有多个参数,而不是再次复制和粘贴函数?
NUnit中的C#示例:

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

    //Act

    //Assert
}

我想在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
    });
});
vdgimpew

vdgimpew1#

另一种方法是使用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);
});
cnjp1d6j

cnjp1d6j2#

您可以将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);
});
5kgi1eie

5kgi1eie3#

如果您使用的是Mocha,则可以将其与mocha-testdata结合使用:

import * as assert from assert;
import { given } from mocha-testdata;

describe('<Foo />', function () {
    given([
        { input: true,  expected: 'some expected value',       description: 'flag enabled' },
        { input: false, expected: 'some other expected value', description: 'flag disabled' },
    ]).
    it('option: enableRemoveControls renders remove controls', function ({ input, expected }) {
        // prepare, act, assert
    });
});

在上面的例子中,你也会注意到一个description字段没有被注入到测试中,这个小技巧可以用来使报告的测试名称更有意义。
希望这有帮助!
一月

相关问题