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:
import { Context } from "mocha";
declare module 'mocha' {
export interface Context {
sayHelloWorld();
}
}
Mocha.Context.prototype.sayHelloWorld = function () {
cy.log('hello world');
};
it('works', function () {
this.sayHelloWorld();
})
Important: For some reason, there is no Context
available in () => {
so you must use function () {
like shown above.