Based on the Cypress documentation, we can run multiple test files using this syntax
cypress run --spec "cypress/e2e/examples/actions.cy.js,cypress/e2e/examples/files.cy.js"
My question is when I have to run 4 of 10 test files in the same folder i have to define like this,
cypress run --spec "cypress/e2e/**/test1.cy.js,cypress/e2e/**/test2.cy.js,cypress/e2e/**/test3.cy.js,cypress/e2e/**/test4.cy.js"
Can we make simplify it, idk is cypress has a feature for defining the spec folder?
So if we can define the folder test spec path like specFolder = cypress/e2e/**/ and I just write script
cypress run --spec "test1.cy.js,test2.cy.js,test3.cy.js,test4.cy.js"
You can run all tests in a specified directory as documented here https://docs.cypress.io/guides/guides/command-line#cypress-run-spec-lt-spec-gt
So try to run all the tests in a directory like so
cypress run --spec "cypress/e2e/**/*
You can use a a little javascript in cypress.config.js to do it, but instead of --spec option specify the tests in an --env variable.
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
if (config.env.specs) { // only if specs are specified on CLI
const specBase = config.specPattern.split('*')[0] // === "cypress/e2e/"
// temporary change to specPattern
config.specPattern = config.env.specs.map(spec=> `${specBase}${spec}`)
}
return config
},
specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}'
},
});
Called with script
// package.json
{
"scripts": {
"cy:specs": "npx cypress run --env specs=[test1.cy.js,test2.cy.js]"
}
}
Run output:
specPattern [ 'cypress/e2e/test1.cy.js', 'cypress/e2e/test2.cy.js' ]
=====================================================================================
(Run Starting)
┌─────────────────────────────────────────────────────────────────────────────────┐
│ Cypress: 12.3.0 │
│ Browser: Electron 106 (headless) │
│ Node Version: v18.12.1 (C:\Program Files\nodejs\node.exe) │
│ Specs: 2 found (test1.cy.js, test2.cy.js) │
│ Searched: cypress/e2e/test1.cy.js, cypress/e2e/test2.cy.js │
└─────────────────────────────────────────────────────────────────────────────────┘
Running: test1.cy.js (1 of 2)
etc
Related
I want to add custom functions to a synpress project. (Synpress is a wrapper around Cypress which allows interaction with Metamask). Note there is a question: Cypress custom command is not recognized when invoked but even though I read through this QA, my custom functions are not recognized.
This is my project setup.
synpress_project/
├─ cypress/
│ ├─ e2e/
│ ├─ support/
├─ package-lock.json
├─ package.json
From the answer mentioned before
All the code and referenced modules in index.js are loaded before your
test file. So you need to refer(require) commands.js in your index.js
file
I obeyed to that, inside cypress/support:
commands.js
import "#testing-library/cypress/add-commands";
// add it here, because custom functions need synpress commands as well
import "#synthetixio/synpress/support";
// add custom functions
Cypress.Commands.add("disconnectFromDappify", () => {
cy.disconnectMetamaskWalletFromDapp().should("be.true");
});
index.js
import './commands'
I know that the files are being read, since removing the line import "#synthetixio/synpress/support"; breaks the tests (metamask interaction does not work anymore). However, my function is not available
TypeError: cy.disconnectFromDappify is not a function
package.json
{
"devDependencies": {
"cypress": "^10.0.1"
},
"scripts": {
"test": "env-cmd -f .env npx synpress run -cf synpress.json"
},
"dependencies": {
"#synthetixio/synpress": "^1.2.0",
"env-cmd": "^10.1.0"
}
}
synpress.json
{
"baseUrl": "http://localhost:3000",
"userAgent": "synpress",
"retries": { "runMode": 0, "openMode": 0 },
"integrationFolder": "cypress/e2e/specs",
"screenshotsFolder": "screenshots",
"videosFolder": "videos",
"video": false,
"chromeWebSecurity": true,
"viewportWidth": 1366,
"viewportHeight": 850,
"component": {
"componentFolder": ".",
"testFiles": "**/*spec.{js,jsx,ts,tsx}"
},
"env": {
"coverage": false
},
"defaultCommandTimeout": 30000,
"pageLoadTimeout": 30000,
"requestTimeout": 30000,
"supportFile": "cypress/support/index.js"
}
Try adding a type definition for your custom command.
I would only expect the TypeError is you're using Typescript, but your file extensions say otherwise.
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable<Subject> {
disconnectFromDappify(): Chainable<any>
}
}
Cypress.Commands.add("disconnectFromDappify", () => {
cy.disconnectMetamaskWalletFromDapp().should("be.true");
});
With help of a colleague, I was able to solve it.
Although, I specified "supportFile": "cypress/support/index.js" inside the synpress.json. It could not find the custom functions.
But if I changed the way the supportFile is called, explicit instead of implicit, it works.
Add --supportFile='cypress/support/index.js' to the end of the command.
"scripts": {
"test": "env-cmd -f .env npx synpress run -cf synpress.json --supportFile='cypress/support/index.js'"
},
Additionally, remove import "#testing-library/cypress/add-commands"; from the commands.js file. (don't know why this is needed, but code breaks, if used, any hints are welcome!)
I am working on a project consisting of three parts: a Client, a Server and a Common directory which contains things I want to import from both the Client and the Server. Everything can use both JS and TS. (Thanks to the babel-typescript preset)
Directory structure
Here is how it looks like:
root/
├── babel.config.js
├── Common/
│ ├── helper1.ts
│ ├── helper2.ts
│ ├── helper3.js
├── Client/
│ ├── src/
│ │ └── file1.js
│ └── .babelrc.js
└── Server/
├── src/
│ └── file1.js
└── .babelrc.js
Babel config files
Here is what my root/babel.config.js looks like:
module.exports = {
presets: ["#babel/preset-typescript"],
plugins: [
["#babel/plugin-transform-for-of", { assumeArray: true }],
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-json-strings",
["#babel/plugin-proposal-decorators", { legacy: true }],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-proposal-export-default-from",
"#babel/plugin-proposal-logical-assignment-operators",
"#babel/plugin-proposal-optional-chaining",
["#babel/plugin-proposal-pipeline-operator", { proposal: "minimal" }],
"#babel/plugin-proposal-nullish-coalescing-operator",
"#babel/plugin-proposal-do-expressions",
"#babel/plugin-proposal-function-bind",
],
};
And here is what my Server/.babelrc.js looks like:
const moduleAlias = require("./tools/module-alias");
const rootConfig = require("../babel.config");
module.exports = {
presets: [
...rootConfig.presets,
[
"#babel/preset-env",
{
targets: {
node: "current",
},
exclude: ["transform-for-of"],
},
],
],
plugins: [
...rootConfig.plugins,
[
"babel-plugin-module-resolver",
{
root: ["."],
alias: moduleAlias.relativeAliases,
extensions: [".js", ".ts"],
},
],
],
};
I will omit the Client/.babelrc.js since it's very similar to the Server one.
Basic test files
Here is an example Common/helper3.js file:
function doubleSay(str) {
return `${str}, ${str}`;
}
function capitalize(str) {
return str[0].toUpperCase() + str.substring(1);
}
function exclaim(str) {
return `${str}!`;
}
const result = "hello" |> doubleSay |> capitalize |> exclaim;
console.log(result);
And inside Server/src/index.js I just import the file Common/helper3.js.
The error
Then, inside the Server directory, I do this:
npx babel-node src/index.js -x .ts,.js
Which prints the following error:
const result = "hello" |> doubleSay |> capitalize |> exclaim;
^
SyntaxError: Unexpected token >
I am definitely sure this error is related to my "strange" directory structure since it's fine when I put this exact file under Server/src.
The question
How can I keep this directory structure and tell Babel to use a config when it processes files within the Common directory?
I don't use Lerna or anything. I have setup special aliases that resolve $common to ../Common where needed. I know there is no issue with this since the file is properly found by Babel (otherwise I would get a "File not found" error)
Note
This babel structure is one of my attempt to fix the issue above. Originally I only had one babel.config.js inside Server and another inside Client. I thought having one at the root would solve this problem but it didn't change anything.
Edit after searching a lot more:
After taking a look at the babel code to find the config parsing, I noticed that this line : https://github.com/babel/babel/blob/8ca99b9f0938daa6a7d91df81e612a1a24b09d98/packages/babel-core/src/config/config-chain.js#L456 is called (null is returned).
I printed everything in this scope and noticed that babel automatically generates an only parameter containing the cwd. (Effectively saying that my babel.config.js doesn't affect my common directory despite being "above" is in the directory hierarchy).
I decided to try overloading it in the command line and arrived at this command:
npx babel-node src/index.js --root-mode upward -x .ts,.js --only .,../Common/ --ignore node_modules
(Added --only and --ignore)
This made me progress a bit: instead of failing to parse advanced syntax (pipeline operator) in js files, it failed on a ts failing, saying
export const accountStatus = Object.freeze({
^^^^^^
SyntaxError: Unexpected token export
What I don't understand is how it can parse the pipeline operator but not the typescript file even though both the pipeline plugin and the typescript are inside the same babel.config.js
Edit after solving this last issue:
Adding --only and --ignore made it work. The other issue was because I forgot to add the #babel/plugin-transform-modules-commonjs plugin and it was not able to resolve the import.
The slight change I did was adding ignore: ["**/node_modules"], to my root babel.config.js file and change my command to use those arguments: --root-mode upward -x .ts,.js --ignore __fake__.
Adding a random --ignore is enough to prevent babel from guessing by itself.
This is the solution I use and it works fine even though it's not very elegant.
I'm using Truffle which has Mocha & Chai included by default.
File tree:
├── test
│ ├── ManagedWallet.js
│ ├── AnotherTest.js
│ └── AndAnotherTest.js
└── truffle.js
This is one of my test file:
var expect = require('chai').expect;
var managedWallet = artifacts.require("./ManagedWallet.sol");
contract('ManagedWallet', function(accounts) {
it("belongs to customer's account address", async function(){
var contract = await managedWallet.deployed();
var customer_account = accounts[1];
var owner = await contract.owner.call();
expect(owner).to.equal(customer_account);
});
});
Since I have a lot of test files inside the test folder, I need to put that var expect = require('chai').expect; line in all the test files.
Is there a way for me to make that expect function available globally without needing me to have that var expect = require('chai').expect; line in all my test files?
I tried putting var expect = require('chai').expect; line inside truffle.js file (above module.exports) but it didn't work and I got ReferenceError: expect is not defined error when I ran the tests.
Example of my truffle.js file (located in the root folder of the project):
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // match any network
}
}
};
Here's my .mocharc.json file that enables this:
{
"spec": "src/**/*.test.ts",
"require": ["esm", "ts-node/register", "chai/register-assert", "chai/register-expect", "chai/register-should"],
"file": "./test-setup.cjs",
"recursive": true
}
I got the answer from GitHub (thanks #keithamus).
require('chai/register-expect');
//... rest of code
expect(...)
My truffle.js looks like:
require('chai/register-expect');
module.exports = {
// the truffle configs
}
And, using expect inside my test files no longer throwing any errors. 🚀
This seems like a basic question but I can't figure out how to do it. This is how to do it in gulp.
I want when I save a file with a jshint error to fail the Grunt build. The output states that jshint failed but Grunt still completes successfully.
grunt.initConfig({
watch: {
js: {
files: ['/scripts/{,**}/*.js'],
tasks: ['newer:jshint:all']
}
}
})
I know there is grunt.fail but how would I use it here?
The following gist will report a jshint error via the CLI and fail to execute any subsequent build steps when saving the .js file.
You will need to adapt according to your requirements :
Directory structure:
project
│
├──package.json
│
├───scripts
│ │
│ └───test.js
│
├─── Gruntfile.js
│
└───node_modules
│
└─── ...
package.json
{
"name": "stack40031078",
"version": "0.0.1",
"description": "Answer to stack question 40031078",
"author": "RobC",
"license": "Apache-2.0",
"devDependencies": {
"grunt": "^1.0.1",
"grunt-contrib-jshint": "^1.0.0",
"grunt-contrib-watch": "^1.0.0",
"grunt-newer": "^1.2.0"
}
}
Gruntfile.js
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// VALIDATE JS
jshint: {
// Note we're using 'src:' instead of 'all:' below.
files: {
src: './scripts/{,**}/*.js'
},
options: {
// Use your jshint config here or define them in
// a separate .jshintrc file and set the flag to:
//
// jshintrc: true
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
smarttabs: true,
globals: {}
}
},
// WATCH THE JS FILES
watch: {
js: {
files: ['./scripts/{,**}/*.js'],
// NOTE: we're not using 'newer:jshint:all' below, just 'newer:jshint'
tasks: ['newer:jshint' /* <-- Add subsequent build tasks here. E.g. ,'concat' - A registered task can also be added. E.g. 'default' */]
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-newer');
grunt.registerTask('default', [
]);
};
test.js
console.log('Hello World');
var test = function() {
return 'test';
};
Testing the demo gist
cd to the project directory
run $ npm install
run $ grunt watch
Open and make a simple edit to test.js, (e.g. add a new line to the end of the file), and save the change.
The CLI reports the error as follows:
Running "jshint:files" (jshint) task
./scripts/test.js
1 |console.log('Hello Universe');
^ 'console' is not defined.
>> 1 error in 1 file
Warning: Task "jshint:files" failed. Use --force to continue.
Aborted due to warnings.
Completed in 0.965s at Fri Oct 14 2016 10:22:59 GMT+0100 (BST) - Waiting...
NOTE:
Any subsequent build tasks specified in the tasks array of the watch.js object, (e.g. concat as per commented in the Gruntfile.js), will not be invoked using this gist as the jshint task fails (... and the concat task has not been defined of course!).
However, when the JavaScript file/s successfully pass the jshint task, any subsequent build tasks that are defined in the tasks array of the watch.js object will be invoked.
I hope this helps!
I have a conventional recommended Intern directory structure:
MyProject
├── node_modules
│ ├── intern-geezer
│ │ ├── client.html
├── src
│ ├── myFunction.js
├── tests
│ ├── intern.js
│ ├── unit
│ │ ├── ps.js
with a very simple config:
useLoader: {
'host-node': 'dojo/dojo',
'host-browser': 'node_modules/dojo/dojo.js'
},
loader: {
packages: []
},
suites: [ 'tests/unit/ps' ]
and tests:
define(function (require) {
var tdd = require('intern!tdd');
var assert = require('intern/chai!assert');
// Global function to test, not an AMD module
var parseF = require('src/myFunction.js');
var he = require('tests/he');
tdd.suite('My tests', function() {
//etc
});
});
````
but when I open the browser client the loader is looking for the test suite inside the intern-geezer directory:
I am not setting a baseUrl in the config (or in the browser URL). I didn't have this trouble going through the regular (non-geezer) intern tutorial. Since the baseUrl defaults to two directories up from client.html I don't see what I'm doing wrong. Thanks for any help. (Yes, I will need geezer for ancient IE. No, I do not want to rewrite the function I'm testing as an AMD module.)
The Intern loader doesn't know how to get to your tests because they haven't been registered as a package. When using the recommended directory structure, you'll want to also set up the recommended loader configuration so that Intern knows where to find your code and tests.
loader: {
packages: [
{ name: 'app', location: 'src/' },
{ name: 'tests', location: 'tests/' }
]
}
Then, update your tests to correctly find the code you need to test.
// Global function to test, not an AMD module
var parseF = require('app/myFunction.js');
Now, Intern should be able to correctly find the code and tests.