在TypeScript中声明Chai自定义插件为NodeJS全局变量。

问题描述 投票:1回答:1

这是我之前的问题

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

因为在我的wdio.conf中 customAssert 是我自己的插件,我需要把它 "添加 "到柴与。use.在这之后,我可以像这样使用我的自定义断言逻辑:chai.customAssert.CustomAssert.CustomAssert.CustomAssert.

当然,我不希望在每个测试中同时导入两个模块,并且 "插入 "我的自定义断言。这就是为什么我在全局范围内声明它的原因。

然而我不知道 如何说服TypeScriptcustomAssert 可以成为 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
    }
  }
}

属性'customAssert'在'ChaiStatic'类型上不存在。 因为我需要通过以下方式将我的插件添加到Chai上 chai.use 首先,我不能在global.d.ts中这样做。

但是我不能在 global.d.ts 中这样做,因为...。语句不允许在环境上下文中使用。

我如何声明NodeJS全局变量的类型,该类型将存在于 chai 只有在我将它插入之后才会出现?

node.js typescript chai webdriver-io
1个回答
0
投票

在你的类型根目录下创建这个文件夹结构

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

索引.d.ts

declare module Chai {
  interface ChaiStatic {
    customAssert: any;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.