【发布时间】:2020-09-02 22:21:16
【问题描述】:
TL;DR:我正在尝试为我的 NodeJS 全局变量声明类型(我在 before 挂钩中设置),
所以 TypeScript 可以识别它。
我的 wdio.conf:
...
let chai = require('chai');
let { customAssert } = require('../helpers/customAssert');
...
before: async function (capabilities, specs) {
// I have accomplished to declare types for this variables thanks to the answer in the previous question
global.foo = "bar"
global.expect= chai.expect;
global.helpers = require("../helpers/helpers");
// ... etc.
// ... etc.
// However I'm stuck with this:
chai.use(customAssert);
global.customAssert = chai.customAssert;
},
因为customAssert 是我自己的插件,我需要用use 将它“添加”到Chai。
在此之后,我可以像这样使用我的自定义断言逻辑:chai.customAssert。
当然,我不想在每个测试中都导入这两个模块,然后“插入”我的自定义断言。这就是我在全局范围内声明它的原因。
但是我不知道如何说服 TypeScript customAssert 可以成为 chai 的一部分 之后我将使用 chai.use 将其插入
global.d.ts
import chai from "chai";
import customAssert from "../helpers/customAssert"
declare global {
const foo: string;
const expect: typeof chai.expect;
const helpers: typeof import("../helpers/helpers");
const customAssert: typeof chai.customAssert // Property 'customAssert' does not exist on type 'ChaiStatic'. Duh...
namespace NodeJS {
interface Global {
foo: typeof foo;
expect: typeof expect;
helpers: typeof helpers;
customAssert: typeof customAssert; // Will not work but let it be
}
}
}
“ChaiStatic”类型上不存在属性“customAssert”,因为我需要先通过chai.use 将我的插件添加到 Chai。
但是我不能在 global.d.ts 中执行此操作,因为 在环境上下文中不允许使用语句。
我如何声明一个 NodeJS 全局变量的类型,它只有在我插入之后才会存在于chai 的范围内?
【问题讨论】:
-
我只是在黑暗中开枪,但也许您可以尝试将
customAssert声明为 Chai 的扩展 (extends)(不确定这是否是正确的方法)跨度> -
假设您使用的是
@types/chai,一个好的开始方法是查看existing typing forchai,确定它们如何定义插件,然后扩充chai 模块以包含您的自定义插件。摸索全局变量不是要走的路 -
@smac89 感谢您的评论。您认为您的建议应该与 zishone 的回答相结合还是另一种方法?
标签: node.js typescript chai webdriver-io