JS function scope defined in object not working for code coverage

I have a function which is defined in side an object. I have used Qunit to write test cases. When I try to generate code coverage report it gives me error var test is not defined.

JS file

$(function(){
var obj = {
        testFunction: function () {
            return true
        }
    }
});

Qunit tests case

QUnit.test("testFunction", function (assert) {
    assert.equal(obj.convertPostCode(), true, "We expect return true");
});

Answer

Firstly $ being jquery, considers first param as a selector, but still executes the function but returns a jquery object back.

secondly, the obj is defined within that function scope and won’t be available in your test scope.

to make it available, define obj outside either in the same level as the test or one or more levels above than the test, set its value inside the function inside $

example

   var obj;
$(function(){
 obj = {
        convertPostCode: function (postcode) {
            var len = postcode.length,
                index = 0;
            switch (len) {
                case 5:
                    index = 2;
                    break;
                case 6:
                    index = 3;
                    break;
                case 7:
                    index = 4;
                    break;
                default:
                    break;
            }
            return postcode.substr(0, index) + " " + postcode.substr(index);
        }
    }
});

Assuming the test is on the same level, you should now have access to obj

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .