是否有任何QUnit断言/函数测试数组中的元素

Is there any QUnit assertion/function who test whether element in array or not

本文关键字:数组 测试 元素 函数 任何 QUnit 断言 是否      更新时间:2023-09-26

我在Qnit函数中有一个预期输出的数组。现在我想测试函数的结果是否在这个数组中。

var a =new array('abc','cde','efg','mgh');

现在我的问题是,是否有任何QUnit断言/函数可以为我做到这一点??

我知道通过一些JS编码,我创建了一个方法来检查这一点,但我只想对OUnit特别好!!!!

如果您有JavaScript 1.6,则可以使用Array.indexOf

test("myFunction with expected value", function() {
    var expectedValues = ['abc','cde','efg','mgh'];
    ok(expectedValues.indexOf(myFunction()) !== -1, 'myFunction() should return an expected value');
});

如果你愿意,你可以扩展QUnit来支持这些断言:

QUnit.extend(QUnit, {
    inArray: function (actual, expectedValues, message) {
        ok(expectedValues.indexOf(actual) !== -1, message);
    }
});

然后您可以在测试中使用这个自定义的inArray()方法:

test("myFunction with expected value", function() {
    var expectedValues = ['abc','cde','efg','mgh'];
    QUnit.inArray(myFunction(), expectedValues, 'myFunction() should return an expected value');
});

我创建了一个jsFiddle来显示这两个选项。

QUnit为此提供了一个deepEqual函数。您可以使用它来比较阵列:
var resultArray = myFunction();
deepEqual(["Expected", "array"], resultArray, "myFunction returned wrong Array");