【发布时间】:2018-11-29 20:44:45
【问题描述】:
通过 WebPack.DefinePlugin 注入的全局变量似乎与我的 Mocha 单元测试不太吻合。运行测试时无法识别全局变量,Mocha documentation 似乎没有办法注入这些全局变量。
如何注入这些变量以便它们在单元测试中起作用?
详细说明
给定一个具有以下配置的 WebPack 项目:
{
...
plugins: [
...
new webpack.DefinePlugin({
__ENV__: JSON.stringify(process.env.ENVIRONMENT),
...
}),
...
]
}
并且在我的项目中有以下打字稿代码:
declare let __ENV__: string;
...
export const ENV = __ENV__;
如果我使用以下选项运行 Mocha:
mocha --compilers ts:ts-node/register --require ./test/entry.ts **/*.test.ts
Mocha 会遇到如下错误:
C:\git\project\src\constants\config.ts:7
export const ENV = __ENV__;
^
ReferenceError: __ENV__ is not defined
at Object.<anonymous> (C:\git\project\src\constants\config.ts:7:20)
...
我尝试了什么
我想我应该在我的entry.ts 文件中定义__ENV__。运行 mocha 时,以下尝试均失败并出现各种错误:
const __ENV__ = 'dev'; // Same message as above.
window.__ENV__ = 'dev'; // Property '__ENV__' does not exist on type 'Window'.
window['__ENV__'] = 'dev'; // ReferenceError: window is not defined
global.__ENV__ = 'dev'; // Property '__ENV__' does not exist on type 'Global'.
export declare let __ENV__ = 'dev'; // Initializers are not allowed in ambient contexts.
export declare const __ENV__ = 'dev'; // Initializers are not allowed in ambient contexts.
【问题讨论】:
-
你解决了吗?
-
对不起@deathangel908 但没有。我改用
Jest,也避免使用WebPack.DefinePlugin。现在(因为它是一个 web 应用程序)我使用代码隐藏来填充window对象,然后在我的Jest设置中,我在beforeAll()中定义了一个测试window对象。 -
该死的。同样的问题。 :(
标签: node.js unit-testing typescript mocha.js