javascriptunit-testingqunit

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


I have an array of my expected output in my Qunit function.Now I want to test that Is my result of function is in this array or not.

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

Now my question is Is there any QUnit assertion/function that can do this for me ??

I know that by some JS coding i create a method to check this but i wanna be spefic to OUnit only !!!!


Solution

  • If you have JavaScript 1.6 you can use 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');
    });
    

    If you want you can extend QUnit to support these kind of assertions:

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

    Then you can use the this custom inArray() method in your tests:

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

    I created a jsFiddle to show both options.