即使我在文件开头声明了 var 语句,单元测试期间 Typescript 仍会抛出变量未定义的错误
Typescript throwing error during unit tests that variable undefined even though I have declare var statement at beginning of file
我正在使用 angular(2) 和打字稿。我正在使用 moment 库来转换日期,所以我的一个实用程序中有这个函数 类:
static isoStringToDateObj(isoDateString: string): Date {
// For unit tests and any environment where moment library is not present
if (!moment) {
return new Date(isoDateString);
}
return moment(isoDateString).toDate();
}
这在浏览器中工作正常,但是当我尝试 运行 我的单元测试时它抛出错误:
ReferenceError:找不到变量:业力测试中的时刻-shim.js(第 16240 行)
它指的是 if (!moment)
行。
- 为什么要关心变量是否存在于声明中
只是检查变量是否存在?它没有引用任何
它的属性。
- 我在顶部有
declare var moment: any;
函数 isoStringToDateObj 所在的文件,为什么会这样
实际声明变量时说引用错误?
检查全局变量是否不存在的唯一正确方法是:
if (typeof moment === 'undefined') { ... }
ReferenceError: Can't find variable: moment
是运行时错误,declare var moment: any
欺骗打字系统对此保持沉默,但不会以任何方式影响实际 moment
全局。
我正在使用 angular(2) 和打字稿。我正在使用 moment 库来转换日期,所以我的一个实用程序中有这个函数 类:
static isoStringToDateObj(isoDateString: string): Date {
// For unit tests and any environment where moment library is not present
if (!moment) {
return new Date(isoDateString);
}
return moment(isoDateString).toDate();
}
这在浏览器中工作正常,但是当我尝试 运行 我的单元测试时它抛出错误: ReferenceError:找不到变量:业力测试中的时刻-shim.js(第 16240 行)
它指的是 if (!moment)
行。
- 为什么要关心变量是否存在于声明中 只是检查变量是否存在?它没有引用任何 它的属性。
- 我在顶部有
declare var moment: any;
函数 isoStringToDateObj 所在的文件,为什么会这样 实际声明变量时说引用错误?
检查全局变量是否不存在的唯一正确方法是:
if (typeof moment === 'undefined') { ... }
ReferenceError: Can't find variable: moment
是运行时错误,declare var moment: any
欺骗打字系统对此保持沉默,但不会以任何方式影响实际 moment
全局。