Search code examples
javascriptnode.jsgruntjsqunit

grunt.js claims NaN where browser doesn't


I'm setting up grunt.js to run qunit tests and for certain tests grunt fails. The failing tests (3 out of 4 tests fail) are all where I'm adding an integer with a string implicitly causing a string concatenation. This works fine if I run the tests manually in a browser, in browser console and in the webpage that uses the code.

What's happening here and how should I tackle it?

grunt output

Running "qunit:all" (qunit) task
Testing html_client/tests.html F..........
>> CommonTests - Test getDateAsString
>> Message: null
>> Actual: "NaN-NaN-NaN"
>> Expected: "1980-02-13"
>> at file:...

>> CommonTests - Test getDateAsString
>> Message: null
>> Actual: "NaN-NaN-NaN"
>> Expected: "1980-12-03"
>> at file:...

>> CommonTests - Test getDateAsString
>> Message: null
>> Actual: "NaN-NaN-NaN"
>> Expected: "1980-02-03"
>> at file:...

test code

    QUnit.test("Test getDateAsString", function() {
        QUnit.equal( Common.getDateAsString(new Date('1980-2-13')), '1980-02-13' );
        QUnit.equal( Common.getDateAsString(new Date('1980-12-3')), '1980-12-03' );
        QUnit.equal( Common.getDateAsString(new Date('1980-12-13')), '1980-12-13' );
        QUnit.equal( Common.getDateAsString(new Date('1980-2-3')), '1980-02-03' );
    });

code

    var getDateAsString = function(date) {
        var dd = date.getDate();
        var mm = date.getMonth() + 1; // January is 0!
        var yyyy = date.getFullYear();

        return yyyy + '-' + ((mm < 10) ? '0' + mm : mm) + '-' + ((dd < 10) ? '0' + dd : dd);
    };

SOLVED

Rewriting the tests as such solved the problem.

    QUnit.test("Test getDateAsString", function() {
        QUnit.equal( Common.getDateAsString(new Date(1980, 1, 13)), '1980-02-13' );
        QUnit.equal( Common.getDateAsString(new Date(1980, 11, 3)), '1980-12-03' );
        QUnit.equal( Common.getDateAsString(new Date(1980, 11, 13)), '1980-12-13' );
        QUnit.equal( Common.getDateAsString(new Date(1980, 1, 3)), '1980-02-03' );
    });

Solution

  • The new Date('1980-2-23') syntax is not supported in every browser. You should use a library if you want consistent results in every browser, like moment.js.

    IE8:

    >> new Date('1980-2-23').getDate() 
    NaN 
    
    >> new Date('1980-02-03').getDate() 
    3