【问题标题】:How to augment the mocha module?如何扩充 mocha 模块?
【发布时间】:2022-08-14 17:12:07
【问题描述】:

鉴于 Cypress 10.3.1 在 devDependencies 中有 Mocha 3.5.3。

我想为 mocha Context 添加新功能。

cypress/support/e2e.ts 我做import \'./context\';。在cypress/support/context.ts 我有:

import { Context } from \'mocha\';

declare module \'mocha\' {
    export interface Context {
        sayHelloWorld();
    }
}

Context.prototype.sayHelloWorld = function () {
    cy.log(\'hello world\');
};

Visual Studio 允许我在 Context 上调用新函数(代码完成)。但是当尝试运行任何测试时,我得到:

Error: Can\'t walk dependency graph: Cannot find module \'mocha\' from \'C:\\…\\cypress\\support\\context.ts\'

这可能是捆绑程序问题吗?如果我删除 browserify 设置(我需要其他设置),我会得到一个不同的错误:

Error: Webpack Compilation Error
./cypress/support/context.ts
Module not found: Error: Can\'t resolve \'mocha\' in \'C:\\…\\cypress\\support\'
…
Field \'browser\' doesn\'t contain a valid alias configuration

我必须手动将 Mocha 安装到我自己的项目中吗?如果我这样做(yarn add -D mocha@3.5.3),我又会得到一个不同的错误:

Cannot read properties of undefined (reading \'prototype\')

知道如何正确执行此操作吗?

    标签: typescript mocha.js cypress module-augmentation


    【解决方案1】:

    解决方案:

    1. 没有import { Context } from "mocha";
    2. 添加这样的新功能:
      declare module 'mocha' {
          export interface Context {
              sayHelloWorld();
          }
      }
      
      Mocha.Context.prototype.sayHelloWorld = function () {
          cy.log('hello world');
      };
      
      1. 现在您可以像这样在测试中使用它们:
      it('works', function () {
          this.sayHelloWorld();
      })
      

      重要的:由于某种原因,() => { 中没有可用的Context,因此您必须使用function () {,如上所示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多