Jest - how can i run only tests within specific matching subfolders? - javascript

I am breaking up my tests into subfolders to represent what "type" of tests they are, like unit tests, or integration tests
how can i configure jest in my CLI command to run tests in subfolders matching src/**/__unit__/**/*.spec.ts?
needs to be within /src folder in the root of project directory
unit can appear in any subfolder of /src
PS> npx jest --testRegex "src\**\__unit__\**\*.spec.ts"
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\Users\ALilland\Documents\dev\controlair\scheduler
75 files checked.
testMatch: - 0 matches
testPathIgnorePatterns: \\node_modules\\ - 75 matches
testRegex: src\**\\__unit__\**\*.spec.ts - 0 matches
Pattern: - 0 matches
it has to be in the CLI argument, because I will have multiple versions in my package.json file representing different types of tests, so i cant add them to the jest.config.js file

The testMatch configuration can do this.
E.g.
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'node',
testMatch: ['<rootDir>/stackoverflow/75262784/src/**/__unit__/**/?(*.)+(spec|test).[jt]s?(x)'],
};
Folder structure:
☁ jest-v26-codelab [main] ⚡ tree -L 4 stackoverflow/75262784
stackoverflow/75262784
└── src
├── client
│ └── index.test.ts
└── server
├── __integration__
│ └── index.test.ts
└── __unit__
└── index.test.ts
5 directories, 3 files
Run jest command, test result:
PASS stackoverflow/75262784/src/server/__unit__/index.test.ts
75262784 - server unit
✓ should pass (2 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.642 s, estimated 9 s
Ran all test suites.

If you have roots like this
apps/folder1/.../
apps/folder2/.../
then you can run all test from folder1 like this.
jest apps/foldeer1/**
then in your jest.config.json
{
...
"moduleFileExtensions": ["js", "json", "ts"],
"roots": [
...,
"<rootDir>/apps/",
...
],
...
}

Related

How to correctly access nested aliases with sass/node-sass in create-react-app

I am trying to break my scss partials into multiple files and aggregate it into one file and access variables accordingly. I have this specific folder structure:
create-react-app/src
│
└───Styles
│ │
│ └───Tokens
│ | │ _Colors.scss
│ | │ _Tokens.scss
│ | _Base.scss
Inside _Colors.scss, I have a simple variable: $primary-color: red;.
// _Colors.scss
$primary-color: red;
Inside _Tokens.scss I use the #use rule to import my partial and give it an alias: #use "./Colors.scss" as colors;.
// _Tokens.scss
#use "./Colors" as colors;
In my _Base.scss I am importing my Tokens.scss and giving that an alias as well: #use "Styles/Tokens/Tokens" as tokens;. I then try to access the nested alias/namespace, eg:
// _Base.scss
#use "Styles/Tokens/Tokens" as tokens;
body {
color: tokens.colors.$primary-color; // Linter has an issue with .colors
}
I am confronted with a linter error: identifier or variable expectedscss(css-idorvarexpected). React also spits out an error:
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: expected "(".
╷
10 │ color: tokens.colors.$primary-color;
│ ^
Confused on what to do at this point, I've tried for a few hours poking around Google but can't find anything. Help would be appreciated, thank you! Let me know if you need any more information!
Have you tried writing "Tokens" in #use "Styles/Tokens/Tokens" as Tokens; lowercase? Because you have it lowercase in the scss below it, color: tokens.colors.$primary-color;

In Cypress, if any test case fails out of automation suite - posttest section in package.json is not executed

Whenever I am executing the whole Cypress suite from the command line to execute a specific folder, when a test case fails during the suite execution the "posttest" section in the package.json file is not executed .
Throws following error.
error Command failed with exit code 3.
In package.json file the script section is as follows
"scripts": {
"pretest": "yarn run [some command]",
"chrome": "yarn run cypress run --browser chrome",
"cypress:open": "cypress open",
"combine-reports": "mochawesome-merge --reportDir cypress\\reports\\mocha > cypress\\reports\\mochareports\\report.json",
"generate-report": "marge cypress\\reports\\mochareports\\report.json -f report -o cypress\\reports\\mochareports",
"report:copyScreenshots": "Xcopy cypress\\screenshots cypress\\reports\\mochareports\\screenshots /E/H/C/I",
"test": "cypress run",
"posttest": "yarn run report:copyScreenshots && yarn run combine-reports && yarn run generate-report"
}
Command executed for command line :
yarn run test --spec "cypress/integration/Demo1/*" --browser chrome
You might want to use the Cypress Module API to invoke cypress run and control the exit code.
This is my script which differs from the docs example slightly,
/scripts/cy-run.js
const cypress = require('cypress')
const args = process.argv.slice(2);
const options = ['cypress', 'run', ...args]; // saves passing 'cypress run' on the command line
cypress.cli.parseRunArguments(options).then(runOptions => {
console.log('runOptions', runOptions)
cypress.run(runOptions).then(() => {
process.exit(0); // control the exit code
}).catch(error => {
console.error(error);
})
}).catch(error => {
console.error(error)
})
package.json
{
...
"scripts": {
"cyrun": "node scripts/cy-run.js",
"postcyrun": "echo next command",
sample test
it('succeeds', () => {
expect(1+1).to.equal(2)
})
it('fails', () => {
expect(1+1).to.equal(3)
})
command line
yarn cyrun --spec "**/test.spec.js" --browser chrome
console output
node scripts/cy-run.js --spec **/test.spec.js --browser chrome
runOptions { browser: 'chrome', spec: '**/test.spec.js' }
==================================================================================================
(Run Starting)
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ Cypress: 5.5.0 │
│ Browser: Chrome 86 │
│ Specs: 1 found (test.spec.js) │
│ Searched: **\test.spec.js │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
... test details
==================================================================================================
(Run Finished)
Spec Tests Passing Failing Pending Skipped
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ × test.spec.js 820ms 2 1 1 - - │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
× 1 of 1 failed (100%) 820ms 2 1 1 - -
$ echo next command
next command // postcyrun is running
Done in 14.35s.
When you use pre- and post-task scripts in your package file:
"scripts": {
"pre<task>": "...",
"<task>": "...",
"post<task>": "...",
...
}
running yarn task (or npm run task) is effectively yarn pre<task> && yarn <task> && yarn post<task> - if any of those steps fails, exits non-zero, the later steps don't run at all.
One pattern I've used to ensure any clean-up happens is the following:
"scripts": {
"pre<task>": "...",
"<task>": "... || (yarn post<task> && exit 1)",
"post<task>": "...",
...
}
For example here you can see where I've used this to ensure that the containers are stopped whether or not the tests fail.
However, note that this will cause issues if you try to pass arguments, e.g. yarn <task> --foo 'bar', because, although they are only passed to <task> not the pre- and post- scripts, there is no way to target the arguments to the ... part rather than the whole command.

gulp-eslint not linting .js files inside of a dot directory

I have .js files inside of a dot directory that are not being linted by gulp-eslint.
Example: .foo/file1.js
I've confirmed that the glob is picking up the files inside of the dot directory.
gulp-eslint is passing successfully for the files inside of a parent dot directory even when an intentional error is introduced inside these files.
I've confirmed that directories without a . in the name of the directory (e.g. src/file.js, etc.) are failing linting, when the same intentional error is introduced.
My project structure is something like this:
project/
│
├── .foo/
│ ├──file1.js
│ └──file2.js
│
├── src/
│ ├──file1.js
│ └──file2.js
│
├── gulpfile.js
└── .eslintrc
Contents of gulpfile.js
const gulp = require('gulp');
const eslint = require('gulp-eslint');
gulp.task('lint', () => {
return gulp.src([ './src/**/*.js', './.foo/**/*.js' ])
.pipe(eslint({
configFile: './.eslintrc'
}))
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
Contents of .eslintrc
// Reducing down to a single, simple rule
{
"env": {
"es6": true
},
"rules": {
"quotes": [
"error",
"single"
]
}
}
Is there something incorrect in my config that is preventing the .js files inside of the dot directory .foo from being linted?
Thanks!
It looks to be a known "quirk" of eslint (as of 6.8.0).
The workaround (until a PR is merged to fix this) is to use an .eslintignore file to unignore dot directories explicitly:
#.eslintignore
!.foo

Run one test file with jest

Installed jest:
yarn add jest
Add a file in ./src/index.js with the content:
test('First test', () => {
expect(true).toBe(true);
});
Try to run it with:
node node_modules/jest/bin/jest.js src/index.js
or
node node_modules/jest/bin/jest.js ./src/index.js
But all I get is:
No tests found
In /home/me/dev/lib
7 files checked.
testMatch: **/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x) - 0 matches
testPathIgnorePatterns: /node_modules/ - 7 matches
Pattern: ./src/index.js - 0 matches
Just would like to run the one file without having to go through the pain of setting up a directory convention or config file. Is this possible?
From Jest's website
Place your tests in a __tests__ folder, or name your test files with a .spec.js or .test.js extension. Whatever you prefer, Jest will find and run your tests.
You can see in the test match
testMatch: **/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x) - 0 matches
It is looking for files that are .spec or .test and end in .js or .jsx
import LoggerService from '../LoggerService ';
describe('Method called****', () => {
it('00000000', () => {
const logEvent = jest.spyOn(LoggerService , 'logEvent');
expect(logEvent).toBeDefined();
});
});
npm test -- tests/LoggerService .test.ts -t '00000000'

Why does a globbed `find` command in Node (execSync) return different results to the CLI?

Example:
╔═ markl#macbook: /var/folders/xp/n5tbdrrs761ck82qqychcf61ptmq9d/T
╚═ ♪ tree tmp.7cHYDVc8rX
tmp.7cHYDVc8rX
├── file
└── subdir
├── anothersubdir
│   └── file
└── file
2 directories, 3 files
╔═ markl#macbook: /var/folders/xp/n5tbdrrs761ck82qqychcf61ptmq9d/T
╚═ ♪ find ./**/*/file -type f
./tmp.7cHYDVc8rX/file
./tmp.7cHYDVc8rX/subdir/anothersubdir/file
./tmp.7cHYDVc8rX/subdir/file
╔═ markl#macbook: /var/folders/xp/n5tbdrrs761ck82qqychcf61ptmq9d/T
╚═ ♪ node
> require('child_process').execSync("find ./**/*/file -type f").toString()
'./tmp.7cHYDVc8rX/subdir/file\n'
> %
╔═ markl#macbook: /var/folders/xp/n5tbdrrs761ck82qqychcf61ptmq9d/T
╚═ ♪ node -v
v7.9.0
You can see there are 3 files I expect it to find (as the CLI does), but in the node repl, it only returns the last file 🤔

Categories