Declare Nodejs global variables in “before” hook in WebdriverIO using TypeScript

旧巷老猫 提交于 2020-06-15 06:06:51

问题


I'm trying to port my JS WDIO project ot TypeScript

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.
    },

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

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
    }
}

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.

How can I migrate my project to TypeScript and continue using my global variables from the before hook?


回答1:


You actually need to augment both the NodeJS.Global interface and global scope

Your global.d.ts will look like this

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;
    }
  }
}

Note that I declared the actual globals const because you only set them by referencing global in your before hook.



来源:https://stackoverflow.com/questions/61676032/declare-nodejs-global-variables-in-before-hook-in-webdriverio-using-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!