Search code examples
javascripttestingmocha.jschaikarma-mocha

Why is my typeof check undefined failing my Mocha test?


This code does not pass the test

Functions:

function setTheme(theme) {
    chartTheme = theme;
}

function getTheme() {
    if (typeof chartTheme === undefined) {
        chartTheme = 'dark';
    }
    return chartTheme;
}

Test:

it('If theme is undefined, expect dark', function() {
    ChartFactory.setTheme(undefined);
    expect(ChartFactory.getTheme()).to.equal('dark');
});

enter image description here

However this does past the test, if I check for "undefined" as a string.

function getTheme() {
    if (typeof chartTheme === 'undefined') {
        chartTheme = 'dark';
    }
    return chartTheme;
}

Solution

  • First of all see Which equals operator (== vs ===) should be used in JavaScript comparisons?

    You're using Strict equality operator with undefined. Strict equality check for both the type and value to be equal.

    typeof returns string.

    Thus,

    typeof chartTheme === 'undefined'
    

    returns true.


    In other words,

    undefined !== 'undefined'
    

    but,

    undefined == 'undefined'.