Reference Error :cy is not defined while running cypress test - cypress

Describe('The Login', function () {
beforeEach(function () {
cy.readFile(Cypress.env('test')).as("user")});
it("Login", () => {
cy.get("#user").then((user) =>
cy.login(user.username, user.password))})
FAIL cypress/integration/login.spec.js
● The Login Page ›
ReferenceError: cy is not defined
at Object.<anonymous> (cypress/integration/login.spec.js:4:5)
at new Promise (<anonymous>)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)

To add some context to the answer by #sai, to resolve this eslint error all I had to do was install eslint-plugin-cypress from here.
npm install eslint-plugin-cypress --save-dev
Then, in my eslint config I added one line to my extends array.
Your config could be .eslintrc.json or the "eslintConfig" configuration object in your package.json
{
"extends": [
"plugin:cypress/recommended"
]
}

Testing locally, this should work for you. Change path of your json file, and use your custom command cy.login. In my example I just printed variables to console.
describe('The Login', () => {
beforeEach(() => {
cy.readFile('cypress/integration/test/test.json').as("user")});
it("Login", () => {
cy.get("#user").then((user) =>
cy.log(user.username, user.pass))
})
})
My test.json was:
{
"username":"test#test.com",
"pass":"pass"
}

The issue was related to eslint
Had to install few packages and made an update to eslintrc files

Related

Cypress test runs localy but fails to run on cypress cloud

So locally my cypress tests run as expected and work fine, but in the cypress cloud they return the following error:
cy.visit() failed trying to load:
/
We failed looking for this file at the path:
/Users/nigel/Documents/portfolio/
The internal Cypress web server responded with:
> 404: Not Found
The tests are written as follows:
describe('Language switcher working', () => {
it('See if the current language is Dutch', () => {
cy.viewport(1496, 1362)
cy.visit('/')
cy.contains('p', 'Ik ben een 2e jaars HBO-ICT Software Engineering student bij de Hogeschool Van Amsterdam.')
})
it('Switch to English', () => {
cy.viewport(1496, 1362)
cy.visit('/')
cy.get('#langSwitcher').select('en')
cy.contains('p', 'I am a second year Software Engineering student at the Amsterdam University of Applied Sciences.')
})
})
The cypress config file has the following content:
import { defineConfig } from "cypress";
export default defineConfig({
projectId: 'gmxneo',
fixturesFolder: "tests/e2e/fixtures",
screenshotsFolder: "tests/e2e/screenshots",
videosFolder: "tests/e2e/videos",
e2e: {
// We've imported your old cypress plugins here.
// You may want to clean this up later by importing these.
setupNodeEvents(on, config) {
return require("./tests/e2e/plugins/index.js")(on, config);
},
specPattern: "tests/e2e/specs/*.cy.{js,jsx,ts,tsx}",
supportFile: "tests/e2e/support/index.js",
},
component: {
devServer: {
framework: "vue-cli",
bundler: "webpack",
},
},
});
The stacktrace is here:
at <unknown> (http://localhost:54356/__cypress/runner/cypress_runner.js:138231:84) at
visitFailedByErr (http://localhost:54356/__cypress/runner/cypress_runner.js:137639:12) at
<unknown> (http://localhost:54356/__cypress/runner/cypress_runner.js:138214:13) at
tryCatcher (http://localhost:54356/__cypress/runner/cypress_runner.js:8914:23) at
Promise._settlePromiseFromHandler
(http://localhost:54356/__cypress/runner/cypress_runner.js:6849:31) at
Promise._settlePromise (http://localhost:54356/__cypress/runner/cypress_runner.js:6906:18) at Promise._settlePromise0
(http://localhost:54356/__cypress/runner/cypress_runner.js:6951:10) at
Promise._settlePromises (http://localhost:54356/__cypress/runner/cypress_runner.js:7027:18) at
_drainQueueStep (http://localhost:54356/__cypress/runner/cypress_runner.js:3621:12) at
_drainQueue (http://localhost:54356/__cypress/runner/cypress_runner.js:3614:9) at
../../node_modules/bluebird/js/release/async.js.Async._drainQueues
(http://localhost:54356/__cypress/runner/cypress_runner.js:3630:5)
at Async.drainQueues (http://localhost:54356/__cypress/runner/cypress_runner.js:3500:14) From Your Spec Code: at
Context.eval (webpack:///./tests/e2e/specs/changeLang.cy.js:6:7)
I tried looking for other people that have this issue, but I couldn't find anything.
I have tried setting a base URL, but then it just waits for my local server to load up and that wont work if i want to integrate it with github actions i think.

converting cypress BDD tests to mocha format

i have suit of BDD tests written in cypress-typescript, which i would like to convert to mocha format. this is contents of a sample test.spec.ts file
///<reference types='cypress'/>
describe('mock test', () => {
console.log('hello i have execuited');
});
this is the contents of cypress.jason file-
{
"testFiles": "**.spec.ts",
"ignoreTestFiles": "cypress/**/*.ts"
}
upon execuition of the command yarn cypress open via the terminal, i can see the tests under the cypress windown but when i try to run them i get this error message-
No tests found.
Cypress could not detect tests in this file.
Error: The service was stopped
at C:\Users\------\IdeaProjects\kura\node_modules\esbuild\lib\main.js:1335:25
at C:\Users\------\IdeaProjects\kura\node_modules\esbuild\lib\main.js:666:9
at Socket.afterClose (C:\Users\------\IdeaProjects\kura\node_modules\esbuild\lib\main.js:644:7)
at Socket.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
any help highly appreciated
The describe() block is simply a way to group our tests, whereas it() blocks are like individual tests.
You need to create individual tests within your describe block like so:
/// <reference types="cypress" />
describe('example to-do app', () => {
it('displays two todo items by default', () => {
console.log('hello i have execuited');
})
it('can add new todo items', () => {
console.log('hello i have execuited');
})
})

Cypress: How to add functions to Mocha Context?

I am trying add functions to this (which is a Mocha Context) in tests, so I can do e.g.
describe('my spec', () => {
it('should work', function () {
this.sayHelloWorld();
})
})
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.
Also in comparison: Again in an empty folder:
yarn add mocha#3.5.3
And in test/test.js:
const { Context } = require("mocha");
it("should work", function () {
Context.prototype.sayHelloWorld = () => console.log("hello world");
this.sayHelloWorld();
});
Now yarn mocha works (says hello world).
What is going on in Cypress? Possibly a bug?
Solution:
no import { Context } from "mocha";
add functions like that:
Mocha.Context.prototype.sayHelloWorld = function () {
cy.log('hello world');
};

how I can run cypress script with the variable provided by user

I have cypress script that runs on different environment and the spec files look like this
describe('Whitelabel Login', () => {
it('Whitelabel Login', () => {
const whitelabelBaseUrl = whitelabelUrl =>
whitelabelUrl.replace('://', '://motivaction.')
cy.visit(whitelabelBaseUrl(Cypress.config('whitelabelUrl')))
cy.screenshot('Whitelbel Login page', { capture: 'fullPage' })
cy.visit(`${whitelabelBaseUrl(Cypress.config('whitelabelUrl'))}/logout`)
cy.screenshot('Whitelbel Logout page', { capture: 'fullPage' })
})
})```
So when I am running the script npx cypress run --env name=qa wl=seedling
then I want `motivaction` to be replaces by seedling is there any way that I can achieve it
You can reference variables passed in through the --env flag in the CLI via Cypress.env('var-name'). Cypress documentation here
const whitelabelBaseUrl = whitelabelUrl.replace('://', `://${Cypress.env('wl')}.`)
Also, pass several env variables using commas and no space. See docs here
npx cypress run --env name=qa,wl=seedling

Cypress error: Could not find any test to run

I am doing a unit test. Cypress now gives an errror. it cannot find the test. but in the login.js file I have written code. I don't understand why it can't find the test, it does exist.
the testcode:
describe("login", () => {
beforeEach(() => {
cy.visit("http://localhost:8080");
});
});
The error:
integration\login.js
We could not detect any tests in the above file. Write some tests and re-run.
Path:
server/cypress/integration/pad/login.js
If this is all of your test code, it really doesn't have any test. Add any 'it' and cypress will recognize it as a test.
describe("login", () => {
beforeEach(() => {
cy.visit("http://localhost:8080");
});
it('Example test', () => {
expect(add(1, 2)).to.eq(3)
})
});
just edit the file... from your project's root folder to bypass cypress. Try that too to test, here it worked.
{
//... other file settings
"exclude": ["src/main/test/cypress"]
}
note: If you are using eslint, you will have to do one more configuration. Since eslint doesn't let us have a TypScrip file inside the project without being treated.
First: Create a file in the project root called tsconfig-eslint.json. It will extend the other tsconfig but ignore the deletion. Put the following content in it:
{
"extends": "./tsconfig.json",
"exclude": []
}
Second: modify the parseOptions of the .eslint.json file to point to the newly created file:
{
//... rest of the settings
"parserOptions": {
"project": "./tsconfig-eslint.json"
},
}

Resources