在“before"中声明 Nodejs 全局变量使用 TypeScript 在 WebdriverIO 中挂钩 [英] Declare Nodejs global variables in "before" hook in WebdriverIO using TypeScript
问题描述
我正在尝试将我的 JS WDIO 项目移植到 TypeScript
I'm trying to port my JS WDIO project ot TypeScript
我在开发过程中遇到了这个问题,TypeScript 无法识别在我的 WDIO 配置中的 before
钩子中声明的 Nodejs 全局变量:
I have faced the issue when during the development TypeScript is not recognizing my Nodejs global variables declared in before
hook in my WDIO config:
...
let chai = require('chai');
...
before: async function (capabilities, specs) {
//setting global variables
global.foo = "bar"
global.expect= chai.expect;
global.helpers = require("../helpers/helpers");
// ... etc.
// ... etc.
},
我遇到了不同的 SO 主题,但似乎它们不相关,因为这里的方法有点不同(因为 before
钩子)...
I came across different SO topics but seems like they are not relevant since the approach here is bit different (because of the before
hook)...
我什至设法在某个时候通过创建 global.d.ts 来使其工作,其中包含以下内容:
I even have manged to get it working at some point by creating global.d.ts with something inside like:
declare module NodeJS {
interface Global {
foo: string
}
}
但是在此打字稿停止识别 WDIO 类型(如 browser
、$
等)之后.而且使用这种方法,我必须在测试中使用 global.foo
,这意味着我必须更改数百次出现的 foo
.
But after this typescript stopped recognizing WDIO types lik browser
, $
etc.
And also with this approach I had to use global.foo
in my tests meaning I have to change hundreds of occurrences of foo
.
如何将我的项目迁移到 TypeScript 并继续使用来自 before
钩子的全局变量?
How can I migrate my project to TypeScript and continue using my global variables from the before
hook?
推荐答案
您实际上需要同时扩充 NodeJS.Global
接口和全局范围
You actually need to augment both the NodeJS.Global
interface and global scope
你的 global.d.ts
看起来像这样
import chai from "chai";
// we need to wrap our global declarations in a `declare global` block
// because importing chai makes this file a module.
// declare global modifies the global scope from within a module
declare global {
const foo: string;
const expect: typeof chai.expect;
const helpers: typeof import("../helpers/helpers");
namespace NodeJS {
interface Global {
foo: typeof foo;
expect: typeof expect;
helpers: typeof helpers;
}
}
}
请注意,我声明了实际的全局变量 const
,因为您只能通过在 before
钩子中引用 global
来设置它们.
Note that I declared the actual globals const
because you only set them by referencing global
in your before
hook.
这篇关于在“before"中声明 Nodejs 全局变量使用 TypeScript 在 WebdriverIO 中挂钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!