unable to add functions to `this` (Context)
See original GitHub issueCurrent behavior
Adding functions to this
(which is a Mocha Context
) yields an error.
Desired behavior
I want to add functions to have them on this
in tests, so I can do e.g.
describe('my spec', () => {
it('should work', function () {
this.sayHelloWorld();
})
})
Test code to reproduce
In an empty folder I call
yarn add cypress
yarn cypress open
so that default config files are created. It also creates a sample test in cypress/e2e/spec.cy.js
.
I can run the sample test without problem. But if I add
import { Context } from "mocha";
to cypress/support/e2e.js
I get
Error: Webpack Compilation Error
./cypress/support/e2e.js
Module not found: Error: Can't resolve 'mocha' in '...\support'
resolve 'mocha' in '...\support'
Parsed request is a module
So I installed Mocha, the same version which is in devDependencies of Cypress (see package.json):
yarn add mocha@3.5.3
My package.json
now looks like this:
{
"dependencies": {
"cypress": "^10.4.0",
"mocha": "3.5.3"
}
}
Now that import
line passes. But this fails:
import { Context } from "mocha";
Context.prototype.sayHelloWorld = () => console.log("hello world");
Error:
> Cannot read properties of undefined (reading 'prototype')
Why is that? In comparison adding something to String.prototype
works.
And it also works in Mocha without Cypress. In another empty folder:
yarn add mocha@3.5.3
And in test/test.js
:
const { Context } = require("mocha");
it("works", function () {
Context.prototype.sayHelloWorld = () => console.log("hello world");
this.sayHelloWorld();
});
Now yarn mocha
works (says hello world).
Why does this work in Mocha but not in Cypress?
Cypress Version
10.4.0
Other
No response
Issue Analytics
- State:
- Created a year ago
- Comments:7
Top GitHub Comments
I found another solution:
(no import)
Hey @iomedico-beyer, thanks for the additional info!
I made a small repo showcasing how you might accomplish this pattern here. The specific changes I made can be seen in this commit.
Let me know if that helps!