【问题标题】:Why is my typeof check undefined failing my Mocha test?为什么我的类型检查未定义未通过我的摩卡测试?
【发布时间】:2016-05-17 15:22:44
【问题描述】:

这段代码没有通过测试

功能:

function setTheme(theme) {
    chartTheme = theme;
}

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

测试:

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

但是,如果我检查 "undefined" 作为字符串,这确实通过了测试。

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

【问题讨论】:

    标签: javascript testing mocha.js chai karma-mocha


    【解决方案1】:

    首先看到Which equals operator (== vs ===) should be used in JavaScript comparisons?

    您正在使用带有undefined 的严格相等运算符。严格相等检查类型和值是否相等。

    typeof 返回 字符串

    因此,

    typeof chartTheme === 'undefined'
    

    返回true


    换句话说,

    undefined !== 'undefined'
    

    但是,

    undefined == 'undefined'.
    

    【讨论】:

    • 谢谢,我想我还是不明白undefined 本身就是一个类型!猜猜我的代码将传递给函数的undefined 转换为字符串。哦,我还用这些基本的默认检查更简单地更新了我的代码:theme = theme || 'dark';
    • @LeonGaban 因为变量的值并没有实际定义。所以,应该有一些价值可以说明这一点。另外,你可以使用 ES6 的默认参数 function setTheme(theme = 'dark') { 而不是 || 'dark'
    • 感谢 ES6 提示!我刚刚尝试过,但在终端 PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Expected token ')' 出现此错误我想我需要某种 Babel 解释器?
    • @LeonGaban 可能。大多数现代浏览器都支持这种语法。见kangax.github.io/compat-table/es6
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2014-07-28
    • 2017-02-19
    相关资源
    最近更新 更多