【问题标题】:Declare Nodejs global variables in "before" hook in WebdriverIO using TypeScript使用 TypeScript 在 WebdriverIO 的“before”钩子中声明 Nodejs 全局变量
【发布时间】:2020-05-08 09:28:06
【问题描述】:

我正在尝试将我的 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 挂钩中的全局变量?

【问题讨论】:

    标签: node.js typescript webdriver-io


    【解决方案1】:

    您实际上需要同时扩充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 来设置它们。

    【讨论】:

    • 谢谢。我会试试这个,并会在赏金结束前给你一个反馈
    • 您能帮我看看我的新问题吗?你的方法对我帮助很大。但是,在声明全局变量的类型之前,我被困在需要“做一些陈述”的地方:stackoverflow.com/questions/61847229/…
    • 好的,我去看看。
    猜你喜欢
    • 2021-06-17
    • 2017-07-25
    • 2022-01-15
    • 2016-05-19
    • 2020-09-02
    • 2019-07-27
    • 2020-02-10
    • 2019-01-04
    • 2020-01-23
    相关资源
    最近更新 更多