Cypress: run only one test - javascript

I want to toggle only running one test, so I don't have to wait for my other tests to see the result of one test.
Currently, I comment out my other tests, but this is really annoying.
Is there a way to toggle only running one test in Cypress?

to run only one file
cypress run --spec path/to/file.spec.js
or using glob patterns:
cypress run --spec 'path/to/files/*.spec.js'
Note: you need to wrap your glob patterns in single quotes to avoid shell expansion!
to run only one test in a file
You can use a .only as described in the Cypress docs
it.only('only run this one', () => {
// similarly use it.skip(...) to skip a test
})
it('not this one', () => {
})
Also, you can do the same with describe and context blocks
edit:
there's also a nice VSCode extension to make adding/removing .only's easier with keyboard shortcuts. It's called Test Utils (install with ext install chrisbreiding.test-utils). It works with js, coffee, and typescript:

There are multiple ways of achieving this.
You can add .onlyto it or describe see #bkucera answer
You can do it from the terminal as explained in the doc here
npx cypress run --record --spec "cypress/integration/my-spec.js"
npm run cypress -- --record --spec "cypress/integration/my-spec.js"

You can mute not needed test suites and particular cases by prepending x to testrunner methods call (describe, it, etc.)
So it would look like:
// this whole testsuite will be muted
xdescribe('Visit google', () => {
it('should visit google', () => { cy.visit('https://google.com/'); });
});
// this testsuite will run
describe('Visit youtube', () => {
it('should visit youtube', () => { cy.visit('https://youtube.com/'); });
// this testcase will be muted
xit('is not necessary', () => { ... });
});

You can run the test like this.
cypress run --spec **/file.js

The best way to do such kind runs are by using the .only keyword that cypress provide.
To run all the test cases in one describe function from many describe functions add the .only in the required describe.
describe("1st describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
describe.only("2nd describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
describe("3rd describe", () => {
it("Should check xx", async function(){
});
it("Should check yy", async function(){
});
});
So here only the 2nd describe will run.
Similarly if you want to run some test cases in 1 describe add the .only in front of all the test cases that you want to run.
describe("describe statement", () => {
it("Should check xx", async function(){
});
it.only("Should check yy", async function(){
});
it.only("Should check zz", async function(){
});
});
So here the it for yy and zz will run
This is similar to the fit and fdescribe in karma and jasmine that you might be familiar with.
You can skip the test in cypress with it.skip or xit

There is one way I have found to skip tests which I don't need to run (in the current test), and that is to use: this.skip();
it('test page', function () {
// skip this test for now
this.skip();
cy.visit('http://example.com/')
cy.contains('test page').click()
cy.url()
.should('include', '/test-page/')
})
1. it is important to use regular function as second argument of it, this will not be available in arrow function
2. Whole of the test will be skipped no matter where we write this.skip()

My test files have a structure like this path/something.test.jsx and commands npx cypress run --spec path/something.test.jsx gives the following exception in the terminal:
Can't run because no spec files were found.
We searched for any files matching this glob pattern:
...
Surprisingly enough the following works and run the test exactly for one file (providing you have jest installed):
jest path/something.test.jsx

A very easy solution is to prefix your tests in with numbers, as testing frameworks will typically will run tests in alpha/numeric order by default - so if I have to check one spec file - I will copy the contents into a file 0-[file-name].spec and re-run the test command. Once the test completes - you terminate the test run - as you will have the results you were looking for. This answer is targeted at projects where your testing framework is abstracted and as a developer, you do not have all available options for your testing framework. Not the best answer, but it works and is intuitive and super easy to do. I have found this to be a way to avoid adding a bunch of conditional skips() or only() calls that will not make it to production, will have to be removed and you can easily add the file pattern to .gitignore file so these local files do not get checked in.

The best-known solution for that already exists and requires adding just one simple argument in the console.
https://github.com/cypress-io/cypress/tree/develop/npm/grep
Simply run:
npx cypress run --env grep="TestName" --spec "filename"
Cypress .only() function is used only for development.

put .only for the test you want to execute and then run the spec as npx cypress run --spec path/to/your-file.spec.js

To run a specific file through Terminal:
npx cypress run --record --spec "cypress/integration/my-spec.js"
npm run cypress -- --record --spec "cypress/integration/my-spec.js"

You can use this
cypress run -- --spec 'path/to/files/*.spec.js'
or
npm run --spec 'path/to/files/*.spec.js'
It worked for me.
Many thanks

use the #focus keyword in the test scripts when execute using cypress open

Related

Async mocha, chai test

I'm running the following test:
it("validates data", (done) => {
Data.run( function(success: boolean) {
expect(success).equal(true);
done();
});
});
When I run the tests this works correctly I get something like this:
✓ validates data (194ms)
However the program never exits until I press cmd+C is that the expected behaviour? When I run any other test with out a callback it exists after all tests are done.
Seems to be a Mocha 4 issue, the only solution they provide is to use the --exit flag. Something like:
mocha --require ts-node/register test/**/*.spec.ts --exit
Not ideal, but works for now.

Getting test results when creating a Karma server programmatically

I am trying to run multiple Karma test files in parallel from inside a Node script and get to know which tests are passing or failing. Right now what I have is this:
const exec = require("child_process").exec;
exec("karma start " + filename, (error, stdout, stderr) => {
// handle errors and test results...
});
The code above works well, and I can get the information on tests passed or failed from stdout. However, it requires having installed Karma and all of the associated dependencies (reporters, browser launchers, etc.) globally. I am looking for a solution that doesn't require me to install all dependencies globally.
My first thought was this:
const karma = require("karma");
const server = new karma.Server(config, () => {
// some logic
});
However, when trying this other approach, I have been unable to gather the test results programmatically.
When using new karma.Server(), is there any way in which I could know which tests have passed or failed (and, ideally, a stack trace of the error)? Alternatively, is there any other way in which I can execute my tests and get the desired information programmatically without the need to install dependencies globally?
Actually, changing the exec line to this seems to do the trick:
exec("node node_modules/karma/bin/karma start " + filename, (error, stdout, stderr) => {
It turns out I'd only need to run the locally installed version of Karma instead of the global one. :-)

Integrating Jest and Rewire

Working on getting a project transitioned over from Mocha to Jest to take advantage of the speed in running tests as well as the Jest framework itself and running into an issue. Rewire is used pretty extensively in the codebase and I'm having an issue when running the gulp-jest task and only for those files that use rewire. I assume it has something to do with modules loading or not loading, but I'm stumped. Here's the really bare-bones gulp task, doesn't have much to it. I've already run through an extensive codemod on the codebase and many tests pass, just not those that use rewire.
gulp.task('jest', function() {
process.env.NODE_ENV = 'test';
return gulp.src('name/path').pipe(
jest({
preprocessorIgnorePatterns: ['<rootDir>/node_modules/'],
automock: false,
resetModules: true,
setupFiles: ['./jestsetup.js']
})
);
});
gulp.task('newtest', function(callback) {
runSequence('env', 'jest', callback);
});
Any time the rewire-related files are run, they complain about the file not being found. Am I missing anything here? I'm certain the modules themselves have the correct path set for the require.
Here's the actual error from jest/rewire:
FAIL path/to/folder/file/app.test.js
● Test suite failed to run
Cannot find module '../../../../path/to/folder/file/app'
at Function.Module._resolveFilename (module.js:469:15)
at internalRewire (node_modules/rewire/lib/rewire.js:23:25)
at rewire (node_modules/rewire/lib/index.js:11:12)
at Object.<anonymous (path/to/folder/file/app.test.js:10:14)
at process._tickCallback (internal/process/next_tick.js:109:7)
Using node 6.X, jest 20.x
Thanks in advance!
Jest has its own mechanism of mocking import, it's called jest.mock.
You will need to switch to using that instead of rewire.
Example
// banana.js
module.exports = () => 'banana';
// __tests__/test.js
jest.mock('../banana');
const banana = require('../banana'); // banana will be explicitly mocked.
banana(); // will return 'undefined' because the function is auto-mocked.
example was taken from here
To my surpise, Proxyquire was not compatible with jest. To mock a dependency you would need to utilize a mocking library, like rewiremock.
Please have a look at this answer and this REPL example on how to successfully mock dependent packages.

Running test cases selectively with Mocha

There is a total of 20 test case files. I want to test a particular set of 10 test cases. Is there any script file or any other method to run the test cases selectively with Mocha?
There are two principal ways to specify a subset of tests to run:
You can give Mocha the name of the file that contains the tests you want to run:
$ mocha path/to/file
It is possible to give paths to multiple files if needed. For instance, if you have 10 test files and want to run all the tests from only 2 of them, you could give the paths of the 2 files.
This method relies on you splitting your tests into separate files according to a logic that suits your situation.
You can use the --grep option:
$ mocha --grep pattern
The pattern is a regular expression that Mocha will use to test each test title. Each test for which the pattern matches will be run.
The two methods could be combined to run only tests that match a pattern and that are from one specific file: $ mocha --grep pattern path/to/file
Following command works for me
$ node_modules/.bin/mocha test/file1.js test/file2.js
mocha.describe("test1", () => {
mocha.it("test1_1", (done) => {
done();
})
mocha.it.only("test1_2", (done) => {
done();
})
})
OutPut :
test2
✔ test2_2 //because of it.only

grunt and qunit - running a single test

I already have grunt-contrib-qunit set up. My Gruntfile.js includes something like this
qunit: { files: ['test/*.html'] }
Now I can run grunt qunit and all my tests run.
Question: how can I run just one single test without running all of them? Is there a way I can overload the value of files from the command line?
You definitely need to look into grunt-contrib-qunit and grunt-contrib-connect (https://github.com/gruntjs/grunt-contrib-qunit and https://github.com/gruntjs/grunt-contrib-connect) as the tandem will provide you with a headless phantom and a local webserver.
UPDATE - as for running just one specific test, you could write something like this, listing your tests as separate targets for your qunit task:
grunt.initConfig({
qunit: {
justSomething: ['test/justsomething.html'],
justSomethingElse: ['test/justsomethingelse.html'],
all: ['test/*.html']
}
});
Then you can call grunt qunit:justSomething, or grunt qunit:all - this is not specific to qunit, though - see http://gruntjs.com/configuring-tasks
Now, if you would really like to use the target to specify a test name, you would go with something like:
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.initConfig({
qunit: {
all: ['test/**/*.html']
}
});
grunt.task.registerTask('foo', 'A sample task that run one test.', function(testname) {
if(!!testname)
grunt.config('qunit.all', ['test/' + testname + '.html']);
grunt.task.run('qunit:all');
});
}
Then call grunt foo:testname.
Yet again, this is not specific to qunit - but rather grunt task writing.
Hope that (finally) helps.

Categories

Resources