使用 TypeScript 在 WebdriverIO 中的 "before" 挂钩中声明 Nodejs 全局变量

Declare Nodejs global variables in "before" hook in WebdriverIO using TypeScript

我正在尝试将我的 JS WDIO 项目移植到 TypeScript

在开发过程中,我遇到了 TypeScript 无法识别我在 WDIO 配置中 before 挂钩中声明的 Nodejs 全局变量的问题:

...
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 挂钩)...

我什至设法在某个时候通过创建 global.d.ts 来让它工作,其中包含以下内容:

declare module NodeJS {
    interface Global {
        foo: string
    }
}

但是在这个打字稿停止识别 WDIO 类型后 browser$ 等。 而且使用这种方法我不得不在我的测试中使用 global.foo 这意味着我必须更改数百次出现的 foo.

如何将我的项目迁移到 TypeScript 并继续使用 before 挂钩中的全局变量?

您实际上需要扩充 NodeJS.Global 接口和全局范围

您的 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 来设置它们。