Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在“中声明Nodejs全局变量”;“之前”;使用TypeScript钩住WebdriverIO_Node.js_Typescript_Webdriver Io - Fatal编程技术网

Node.js 在“中声明Nodejs全局变量”;“之前”;使用TypeScript钩住WebdriverIO

Node.js 在“中声明Nodejs全局变量”;“之前”;使用TypeScript钩住WebdriverIO,node.js,typescript,webdriver-io,Node.js,Typescript,Webdriver Io,我正在尝试将我的JS WDIO项目移植到TypeScript 在开发过程中,TypeScript无法识别WDIO配置中beforehook中声明的Nodejs全局变量时,我遇到了一个问题: ... let chai = require('chai'); ... before: async function (capabilities, specs) { //setting global variables global.foo = "bar" gl

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

在开发过程中,TypeScript无法识别WDIO配置中
before
hook中声明的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主题,但似乎它们不相关,因为这里的方法有点不同(因为
之前的
钩子)

我甚至设法在某个时候通过创建global.d.ts让它工作起来,其中包括:

declare module NodeJS {
    interface Global {
        foo: string
    }
}
但在此类型脚本停止识别WDIO类型后,如
浏览器
$
等。 同样,使用这种方法,我必须在测试中使用
global.foo
,这意味着我必须更改数百次出现的
foo


如何将我的项目迁移到TypeScript,并继续使用
之前的
钩子中的全局变量?

您实际上需要增加
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
,因为您仅通过在
挂钩之前的
中引用
全局变量来设置它们。

谢谢。我会尝试一下,在赏金结束前给你一个反馈。你能帮我看看我的新问题吗。你的方法帮了我很多忙。然而,在声明全局变量的类型之前,我需要“执行一些语句”:是的,我将看一看。