【问题标题】:Is there any QUnit assertion/function who test whether element in array or not是否有任何 QUnit 断言/函数来测试数组中的元素是否
【发布时间】:2013-02-11 07:05:08
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript unit-testing qunit


    【解决方案1】:

    如果你有 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');
    });
    

    我创建了a jsFiddle to show both options

    【讨论】:

      【解决方案2】:

      QUnit 为此提供了 deepEqual 函数。 您可以使用它来比较数组:

      var resultArray = myFunction();
      deepEqual(["Expected", "array"], resultArray, "myFunction returned wrong Array");
      

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        • 2014-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-02
        相关资源
        最近更新 更多