javascript - 为什么我的 typeof 检查 undefined 没有通过我的 Mocha 测试?

标签 javascript testing mocha.js chai karma-mocha

这段代码没有通过测试

函数:

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');
});

enter image description here

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

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

最佳答案

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

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

typeof 返回 string

因此,

typeof chartTheme === 'undefined'

返回 true


换句话说,

undefined !== 'undefined'

但是,

undefined == 'undefined'.

关于javascript - 为什么我的 typeof 检查 undefined 没有通过我的 Mocha 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37280302/

相关文章:

javascript - 类型错误:queryClient.defaultQueryObserverOptions 不是函数

c# - 通过 visual studio 并行测试执行,测试被跳过

google-chrome - 如何在机器人框架中设置路径 chrome 驱动程序?

python - 在 Django 中测试 url 重定向

node.js - Mockgoose 测试失败导致 MongoError : topology was destroyed

javascript - Internet Explorer 9 对象检测

javascript - 无法加载 <资源> : No 'Access-Control-Allow-Origin' header is present on the requested resource

javascript - Protractor - 查找所有元素和找到的元素的循环长度,然后单击按钮

javascript - 防止使用 ng-model 进行动态更改

javascript - 确保 "done()"被称为JS错误