Mocha ignores existing .mocharc.js config file - javascript

Here is my "scripts" section of package.json:
"scripts": {
"pretest": "eslint \"**/*.js\" --ignore-pattern node_modules/",
"test": "mocha"
}
and here is my .mocharc.js:
'use strict';
module.exports = {
diff: true,
extension: ['js'],
package: './package.json',
reporter: 'landing',
slow: 75,
timeout: 2000,
ui: 'bdd',
watchFiles: ['src/tests/*.js', 'src/tests/**/*.js'],
};
When running npm test I get pretest running correctly, but mocha seems to ignore config file. Haven't seen the issue anywhere yet.

Try running Mocha with --config options.
Example: mocha --config .mocharc.js
And your watchFiles option is wrong. It should be watch-files.
See this mocha example: https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js

Try adding the following to your .mocharc.js
recursive: true

Related

How to find aliases in Global Jest setup?

I want to run some stuff only once before all test cases. Therefore, I have created a global function and specified the globalSetup field in the jest configuration:
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
However, within globalSetup, I use some aliases # and Jest complains it does not find them.
How can I run globalSetup once the aliases have been sorted out?
My Jest configuration is as follows:
module.exports = {
rootDir: rootPath,
coveragePathIgnorePatterns: ['/node_modules/'],
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
globals: {},
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'json'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' })
};
When I run testSetup before every test, it runs ok the aliases, but this does not happen with globalSetup.
Any clue what could I do?
I managed to get this work by including tsconfig-paths/register at the top of my globalSetup file:
// myGlobalSetupFile.ts
import 'tsconfig-paths/register';
import { Thing } from './place-with-aliases';
export default async () => {
await Thing.doGlobalSetup();
}
You have to make sure you have tsconfig-paths installed in your project.
Unfortunately I have found there is no solution for this based on the comments on this issue:
https://github.com/facebook/jest/issues/6048
The summary is that globalSetup runs outside of Jest ecosystem and therefore it will not recognize the aliases, etc.
There are several workarounds, for example, if your npm run test command is something like this:
"test": "jest --config config/jest.config.js --detectOpenHandles --forceExit"
Then you can do something like:
"test": "node whateverBeforeJest.js && jest --config config/jest.config.js --detectOpenHandles --forceExit"

How to set env in package.json which is used within .bablerc

I am trying to run Jest tests as part of a script before I then run webpack, like this.
npm run test
webpack --progress --profile --watch --mode development
Jest only works with compiled code, so I had set my .babelrc to the following, which worked, however then it transpiled all my code in webpack which I didn't want, in development mode I want to leave the JavaScript un-transpiled so I can work with it without it being obfuscated.
{
"presets": [ "#babel/preset-env" ]
}
Instead I want to run Jest by calling 'npm run test' which then I can specify only that script transpiles the code and then webpack runs without transpiling, I was hoping something like this in my .babelrc file
{
"env": {
"test": {
"presets": [ "#babel/preset-env" ]
}
}
}
Then in my package.json I could set the env to test which then would leave webpack alone.
"scripts": {
"test": "SET env=test&& jest --config jest.config.js"
}
With this setup I still get the following message appearing when 'npm run test' runs which shows the babelrc file isn't being hit.
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
Can anyone help?
So turns out my test was ok in the .babelrc file
{
"env": {
"test": {
"presets": [ "#babel/preset-env" ]
}
}
}
And the script needed in my package.json was this without setting any node env
"scripts": {
"test": "jest --config jest.config.js"
}
It was actually my webpack script that wasn't configured correctly, I needed to add '--env.NODE_ENV=development' at the end
webpack --progress --profile --watch --mode development --env.NODE_ENV=development
Which could then be checked within my webpack.config file.
module.exports = (env) => {
const isDevelopment = env && env.NODE_ENV === 'development';
...
then in my rules test for isDevelopment
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: isDevelopment ? {} : { presets: ['#babel/preset-env'] }
}
},

Using webpack aliases in AVA tests

I need to include the aliases from webpack into AVA when it runs.
I used webpack's resolve.alias to access all the files under src folder:
webpack.config.js
resolve: {
alias: {
'#': path.resolve(__dirname, 'src/'),
},
},
and then that # special prefix for my own modules like this:
my-module.js
import main from '#/view/main'
This is my AVA configuration:
package.json
"scripts": {
"test-unit": "ava test/unit"
},
"ava": {
"require": ["esm"]
},
Is possible to add something to package.json like in this mocha solution?
https://stackoverflow.com/a/42989394/12361834
Thank you so much for your time and help!
If I understood you well you can do it with link-module-alias npm package.
Add this to your package.json:
"scripts": {
"postinstall": "link-module-alias",
"preinstall": "command -v link-module-alias && link-module-alias clean || true"
"test": "ava"
},
"_moduleAliases": {
"#": "src"
}
npm i && npm test
If you need further details you can download a working example here.

Eslint: warning File ignored by default. Use a negated ignore pattern

I am new in using Eslint.
So far I have installed Eslint in my local project and configured it. The eslintrc.js file contains
module.exports = {
env: {
node: true,
commonjs: true,
es6: true,
mocha: true,
},
extends: [
'airbnb-base',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaVersion: 2018,
},
rules: {
},
};
And in package.json I have
"scripts": {
"lint": "eslint .eslintrc.js --fix",
}
In terminal I run
npm run lint
And the output is
> apigateway#1.0.0 lint C:\nodeprojects\restapi
> eslint .eslintrc.js --fix
C:\nodeprojects\restapi\.eslintrc.js
0:0 warning File ignored by default. Use a negated ignore pattern (like "--ignore-pattern '!<relative/path/to/filename>'") to override
But if I run
eslint <foldername> --fix then it works.
I am using webstorm IDE and in windows os.
Any help is highly appreciated.
ESlint default behaviour is ignoring file/folders starting with . - https://github.com/eslint/eslint/issues/10341.
In case for example you want to lint .storybook folder, ESLint will ignore it by default. To lint it, .eslintrc.js must include:
{
...
// Lint ".storybook" folder (don't ignore it)
"ignorePatterns": ["!.storybook"],
...
}
Because of that default ESLint behaviour, I do in all my projects like this (lint whole project from the root) :
{
...
// ESlint default behaviour ignores file/folders starting with "." - https://github.com/eslint/eslint/issues/10341
"ignorePatterns": ["!.*", "dist", "node_modules"],
...
}
Where I first don't ignore any file/folder starting with . and then I exclude folders that I actually want to ignore.
Your npm script runs the linter on the .eslintrc.js file and this file is as the comment says File ignored by default.
You need to change the lint script from:
"lint": "eslint .eslintrc.js --fix",
to:
"lint": "eslint <foldername> --fix"
Where <foldername> is the correct folder.
I ran into this issue where the pre-commit Husky hook would try to scan this file when trying to commit merges (where someone changed .eslintrc.js previously), then this would fail the merge commit in team members' local envs (file ignored by default)
You can create a .eslintignore file next to .eslintrc.js. Then in .eslintignore put:
!.eslintrc.js

How to cover React jsx files in Istanbul?

I'm trying to integrate my existing test processes to now include React, but am struggling on the code coverage part. I've been able to get my unit tests working fine by following this project/tutorial - https://github.com/danvk/mocha-react - http://www.hammerlab.org/2015/02/14/testing-react-web-apps-with-mocha/
I've been using Istanbul to cover my node code and it's working pretty well. However, I'm having trouble getting it to cover the jsx files that I'm using in my tests.
Here's an example of an existing Istanbul task, which also runs fine on vanilla js (node backend code)
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
gulp.task('test-api', function (cb) {
gulp.src(['api/**/*.js'])
.pipe(istanbul()) // Covering files
.pipe(istanbul.hookRequire()) // Force `require` to return covered files
.on('finish', function () {
gulp.src(['test/api/*.js'])
.pipe(mocha())
.pipe(istanbul.writeReports()) // Creating the reports after tests runned
.on('end', cb);
My issue ( i think ) is I can't get Istanbul to recognize the jsx files or they're not being compared to what was run in the tests. I tried using the gulp-react module to precompile the jsx to js so it can be used by Istanbul, but I'm not sure if it's working. It's not being covered somehow and I'm not sure where the issue is.
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var react = require('gulp-react');
gulp.task('test-site-example', function (cb) {
gulp.src(["site/jsx/*.jsx"]) //Nothing is being reported by Istanbul (not being picked up)
.pipe(react()) //converts the jsx to js and I think pipes the output to Istanbul
.pipe(istanbul())
.pipe(istanbul.hookRequire()) // Force `require` to return covered files
.on('finish', function () {
gulp.src(['test/site/jsx/*.js'], { //tests run fine in mocha, but nothing being shown as reported by mocha (not covered)
read: false
})
.pipe(mocha({
reporter: 'spec'
}))
.pipe(istanbul.writeReports())
.on('end', cb);
});
;
});
Any ideas what I'm doing wrong? Or any clue on how to integrate a test runner (preferably Istanbul) into a Gulp-Mocha-React project?
Add a .istanbul.yml file to your app root and add .jsx to extensions "extension"...
Here is what I did.
// File .istanbul.yml
instrumentation:
root: .
extensions: ['.js', '.jsx']
To kickstart istanbul and mocha with jsx
$ istanbul test _mocha -- test/**/* --recursive --compilers js:babel/register
This will convert your .jsx files to .js and then istanbul will cover them.
I hope this helps. It worked for me.
There is a library you can take a look at, gulp-jsx-coverage (https://github.com/zordius/gulp-jsx-coverage).
In case someone else is having the same problem and solutions above don't work, I found that adding a simple "-e .jsx" tag worked:
"scripts": {
"start": "meteor run",
"test": "NODE_ENV=test mocha --recursive --compilers js:babel-register --require tests/index.js ./tests/**/*.test.js",
"coverage": "NODE_ENV=test nyc -all -e .jsx npm test"
}
This solution was found at: http://www.2devs1stack.com/react/tape/testing/nyc/coverage/2016/03/05/simple-code-coverage-with-nyc.html
A great tutorial can be found at https://istanbul.js.org/docs/tutorials/es2015/
I just slightly modified it to include react. (I also used 'env' instead of 'es2015', but either should work.) Here are my configurations:
npm i babel-cli babel-register babel-plugin-istanbul babel-preset-env babel-preset-react cross-env mocha nyc --save-dev
.babelrc
{
"presets": ["env", "react"],
"env": {
"test": {
"plugins": [
"istanbul"
]
}
}
}
package.json
"scripts": {
"test": "cross-env NODE_ENV=test nyc mocha test/**/*.spec.js --compilers js:babel-register"
}
"nyc": {
"require": [
"babel-register"
],
"reporter": [
"lcov",
"text"
],
"sourceMap": false,
"instrument": false
}

Categories