typescriptmocha.jscypressmodule-augmentation

How to augment the mocha module?


Given Cypress 10.3.1 which has Mocha 3.5.3 in devDependencies.

I want to add new functions to mocha Context.

In cypress/support/e2e.ts I do import './context';. And in cypress/support/context.ts I have:

import { Context } from 'mocha';

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

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

Visual Studio lets me call the new function on Context (code completion). But when trying to run any test I get:

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

Is this possibly a bundler issue? If I remove the browserify setup (which I need for something else), I get a different error instead:

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

Do I have to install Mocha manually to my own project? If I do so (yarn add -D mocha@3.5.3), again I get a different error instead:

Cannot read properties of undefined (reading 'prototype')

Any idea how to do this right?


Solution

  • Solution:

    1. no import { Context } from "mocha";
    2. add new functions like that:
    declare module 'mocha' {
        export interface Context {
            sayHelloWorld();
        }
    }
    
    Mocha.Context.prototype.sayHelloWorld = function () {
        cy.log('hello world');
    };
    
    1. now you can use them in your tests like that:
    it('works', function () {
        this.sayHelloWorld();
    })
    

    Important: For some reason, there is no Context available in () => { so you must use function () { like shown above.