Cypress error: Could not find any test to run - cypress

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"
},
}

Related

cy.task gives an error but no explanation, how can I fix it?

I'm using Cypress for frontend testing and I defined a task in cypress.config file.
setupNodeEvents(on) {
on('task', {
downloads: downloadspath => {
return fs.readdirSync(downloadspath);
},
deleteFiles: directory => {
const files = fs.readdirSync(directory);
if (files.length === 0) {
return 0;
}
for (const file of files) {
fs.unlinkSync(path.join(directory, file));
}
return 0;
},
});
},
And when I use it in my tests, it gives an error like this:
There's no explanation so, I don't know how to fix this error.
cy.task does a simple work, it just deletes all files in the cypress/downloads folder.
Generally, if the task throws an error it shows up in the Cypress log. You may get more info if you open devtools and click on the Cypress log entry.
Specifically, fs.unlinkSync(path.join(directory, file)) is probably failing because there is a sub-directory in the directory, see Node.js fs.unlinkSync() Method
The fs.unlinkSync() method is used to synchronously remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory.
Since you are deleting cypress/downloads in the test, be aware Cypress does that for you
Cypress Configuration - Downloads
trashAssetsBeforeRuns (default: true)
Whether Cypress will trash assets within the downloadsFolder, screenshotsFolder, and videosFolder before tests run with cypress run.

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 do I change the filename of the Junit XML report that Nightwatch.js generates?

I have a Nightwatch.js test suite running. When it completes, I've configured the output directory using the output_folder setting. It produces JUnit XML files in that directory correctly. I have an existing automation tool which scans the directory for JUnit test XML files and reports on them. Unfortunately it only matches files in the directory with a naming scheme: TEST-.xml. Let's assume that I can't change the matching rules on my automation tool. I'm looking for a way to add "TEST-" as a prefix to my tests. Ideally I can do this by configuring Nightwatch. Does Nightwatch support this configuration? I can't find any such options.
I ended up changing my test scripts in package.json so that they did a rename after the test was run. Here is what they were before:
{
// ...
"scripts": {
"integ-tests": "<some nightwatch command>"
}
// ...
}
Here is what they were after:
{
// ...
"scripts": {
"rename-integ-tests": "node -e \"require('fs').readdir('<my test directory>', (err, files) => { files.forEach(file => { if(file.endsWith('.xml') && ! file.startsWith('TEST-')) { fs.rename('<my test directory>' + file, '<my test directory>/TEST-' + file, function(err) { if (err) console.log(err); console.log('Renamed Smoke Test: ' + file + ' to TEST-' + file) }) } }); });\"",
"private-integ-tests": "<some nightwatch command>",
"integ-tests": "npm run private-integ-tests && npm run rename-integ-tests"
}
// ...
}

Directory path is incorrect when running from cypress test runner

When I login from normal browser the login is successful with the URL : http://neelesh.zapto.org:8084/EnrolMe/indHome.html
But when I run the script from Cypress the directory location is not appended and the new URL after login is formed as : http://neelesh.zapto.org:8084/__/indHome.html
I have tried setting cypress.json with
{
"chromeWebSecurity": false,
"modifyObstructiveCode" : false
}
I have tried on chrome/electron(head and headless).
Below is my code snippet:
describe('My First Test Suite', function() {
it('My First test case', function() {
cy.visit("http://neelesh.zapto.org:8084/EnrolMe")
cy.get("#login").click()
cy.get("input[value='Individual']").click()
cy.get("#username").type('1234567890')
cy.get("#pwd").type('0646')
Cypress.Cookies.debug(true)
cy.clearCookies()
cy.get("#login").click()
cy.wait(6000)
})
})
When I run the script from Cypress the directory location is not appended and the new URL after login is formed as : http://neelesh.zapto.org:8084/__/indHome.html
It should be redirected as : http://neelesh.zapto.org:8084/EnrolMe/indHome.html
Can anyone help me on this?
This sounds like an issue with "Frame Busting". There's a related discussion for Cypress GitHub Issue #992 which may lend some help.
Your application code may contain problematic frame busting code like the following:
if (window.top !== window.self) {
window.top.location.href = window.self.location.href;
}
You can get around this by changing your application code's reference to window.self from the Application Window to the Cypress Test Runner window (window.top).
Cypress emits a series of events as it runs in your browser. You can use the emitted window:before:load application event to ensure it's done before you attempt to login.
// cypress/support/index.js
Cypress.on('window:before:load', (win) => {
Object.defineProperty(win, 'self', {
get: () => {
return window.top
}
})
})

How to test browserify project using karma/jasmine

I'm totally new to the concept of testing, and i need one solid example on how to do it in my project:
I have a gulp file goes like this (Not all of it, just the important portions)
gulp.task('bundle', function() {
gulp.src('public/angular-app/main.js')
.pipe(browserify({
debug: true
}))
.pipe(gulp.dest('public/min-js'));
});
This is a slight portion of my main.js:
'use strict';
angular.module('myApp', [
'ui.router',
'ui.bootstrap',
'ngSanitize',
'ngFx',
...
], ['$interpolateProvider',
function($interpolateProvider) {
$interpolateProvider.startSymbol('{{');
$interpolateProvider.endSymbol('}}');
}
])
.config(require('./config/routes'))
.config(require('./config/authInterceptor'))
.run(require('./config/runPhase'))
.run(require('./config/xeditable'))
.controller('homeController', require('./controllers/homeController'))
.controller('modalInstanceCtrl', require('./controllers/modalInstanceCtrl'))
.controller('modalparticipantCtrl',require('./controllers/modalParticipantCtrl'))
.controller('generatorController',require('./controllers/generatorController'))
.controller('navController', require('./controllers/navController'))
.controller('signInController', require('./controllers/signInController'))
.controller('pricingController', require('./controllers/pricingController'))
.controller('howItWorksController',require('./controllers/howItWorks'))
...
Now this is my config file for karma:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/angular-app/**/*.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
When i run karma with karma start this is what i get:
Uncaught reference error:require is not defined
at root/public/angular-app/main.js
So my question is simple, how can i do tests, for example, on my homeController...
//update
So I updated my test file to this:
describe("An Angularjs test suite",function(){
var target, rootScope;
beforeEach(inject(function($rootScope) {
rootScope = $rootScope;
// Mock everything here
spyOn(rootScope, "$on")
}));
beforeEach(inject(function(homeController) {
target = homeController;
}));
it('should have called rootScope.$on', function(){
expect(rootScope.$on).toHaveBeenCalled();
});
});
and my config file to this:
// list of files / patterns to load in the browser
files: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/angular/angular.js',
'public/vendor/angular-mocks/angular-mocks.js',
'public/min-js/main.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
},
Still nothing works, first he says 'unknown provider homeControllerProvider',
Now if i delete them lines:
beforeEach(inject(function(homeController) {
target = homeController;
}));
it still gives me error, expected spy $on to be called, How do i fix this?
You need to inform Karma to run Browserify before running tests.
You can add this in your Karma config:
{
browserify: {
watch: true,
debug: true
},
preprocessors: {
'test/*': ['browserify']
}
}
Karma config file reference: http://karma-runner.github.io/0.12/config/configuration-file.html
Or have a look at one of of my projects that uses Karma for testing: smild.

Resources