问题
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