【问题标题】:Declare Chai custom plugin as a NodeJS global variable in TypeScript在 TypeScript 中将 Chai 自定义插件声明为 NodeJS 全局变量
【发布时间】:2020-09-02 22:21:16
【问题描述】:

Here is my previous question

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 for chai,确定它们如何定义插件,然后扩充chai 模块以包含您的自定义插件。摸索全局变量不是要走的路
  • @smac89 感谢您的评论。您认为您的建议应该与 zishone 的回答相结合还是另一种方法?

标签: node.js typescript chai webdriver-io


【解决方案1】:

在您的类型根目录中创建此文件夹结构

.
└── chai/
    └── index.d.ts             

index.d.ts

declare module Chai {
  interface ChaiStatic {
    customAssert: any;
  }
}

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 1970-01-01
    • 2022-01-15
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多