我有以下 JavaScript 代码:
if (Notification.permission !== 'granted') {
return Notification.permission
}
当我对一些使用它的代码运行 Mocha 测试时,测试失败:
ReferenceError: Notification is not defined
我认为我可以通过这样做来完成这项工作:
sinon.stub(Notification, 'permission')
但是,我仍然遇到同样的错误。
如何防止此错误?
最佳答案
在运行 Notification.permission
之前,您应该首先测试 Notification
是否存在。
一种方法是替换...
if (Notification.permission !== 'granted') {
return Notification.permission
}
...用这个:
if (typeof Notification !== typeof undefined && Notification.permission !== 'granted') {
return Notification.permission
}
关于javascript - 如何测试调用窗口对象的javascript代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43091401/