How to get the code coverage report using Jest? - javascript

Is there a way to have code coverage in the JavaScript Jest testing framework, which is built on top of Jasmine?
The internal framework does not print out the code coverage it gets. I've also tried using Istanbul, blanket, and JSCover, but none of them work.

When using Jest 21.2.1, I can see code coverage at the command line and create a coverage directory by passing --coverage to the Jest script. Below are some examples:
I tend to install Jest locally, in which case the command might look like this:
npx jest --coverage
I assume (though haven't confirmed), that this would also work if I installed Jest globally:
jest --coverage
The very sparse docs are here
When I navigated into the coverage/lcov-report directory I found an index.html file that could be loaded into a browser. It included the information printed at the command line, plus additional information and some graphical output.

UPDATE: 7/20/2018 - Added links and updated name for coverageReporters.
UPDATE: 8/14/2017 - This answer is totally outdated. Just look at the Jest docs now. They have official support and documentation about how to do this.
#hankhsiao has got a forked repo where Istanbul is working with Jest. Add this to your dev dependencies
"devDependencies": {
"jest-cli": "git://github.com/hankhsiao/jest.git"
}
Also make sure coverage is enabled in your package.json jest entry and you can also specify formats you want. (The html is pretty bad ass).
"jest": {
"collectCoverage": true,
"coverageReporters": ["json", "html"],
}
See Jest documentation for coverageReporters (default is ["json", "lcov", "text"])
Or add --coverage when you invoke jest.

Jan 2019: Jest version 23.6
For anyone looking into this question recently especially if testing using npm or yarn directly
Currently, you don't have to change the configuration options
As per Jest official website, you can do the following to generate coverage reports:
1- For npm:
You must put -- before passing the --coverage argument of Jest
npm test -- --coverage
if you try invoking the --coverage directly without the -- it won't work
2- For yarn:
You can pass the --coverage argument of jest directly
yarn test --coverage

This works for me:
"jest": {
"collectCoverage": true,
"coverageReporters": ["json", "html"]
},
"scripts": {
"test": "jest --coverage"
},
Run:
yarn/npm test

You can run npx jest --coverage -- path/to/your/file.spec.js
that will show coverage for affected files
If you want to view this in browser you can do as follows,
Go to Browser and CMD+O.
Navigate to your repo and search for coverage/lcov-report/index.html
Then you can visually see all the coverage areas.
You can also refer to this link below, for more information
https://dev.to/stevescruz/awesome-jest-tip-coverage-report-h5j

Check the latest Jest (v 0.22): https://github.com/facebook/jest
The Facebook team adds the Istanbul code coverage output as part of the coverage report and you can use it directly.
After executing Jest, you can get a coverage report in the console and under the root folder set by Jest, you will find the coverage report in JSON and HTML format.
FYI, if you install from npm, you might not get the latest version; so try the GitHub first and make sure the coverage is what you need.

If you are having trouble with --coverage not working it may also be due to having coverageReporters enabled without 'text' or 'text-summary' being added.
From the docs: "Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output." Source

Configure your package.json file
"test": "jest --coverage",
Now run:
yarn test
All the test will start running and you will get the report.

I had the same issue and I fixed it as below.
install yarn npm install --save-dev yarn
install jest-cli npm install --save-dev jest-cli
add this to the package.json "jest-coverage": "yarn run jest -- --coverage"
After you write the tests, run the command npm run jest-coverage. This will create a coverage folder in the root directory. /coverage/icov-report/index.html has the HTML view of the code coverage.

Related

React / Jest get coverage from a single component not all - current approach not working

I have tried this answer to get coverage for a single component but it is not working. The test runs only for that component but no coverage?
Is there some other configuration that needs to be done anywhere?
I have tried:
npm test src/components/component1/my-component.test.tsx --coverage --collectCoverageFrom=src/components/component1/my-component.test.tsx
Anything I am doing wrong?
The collectCoverageFrom takes in glob patterns as argument, so you need adjust that path string with "".
I have successfully run this command with code coverage from one file with
node_modules/.bin/jest ComponentTest.test.ts --coverage --collectCoverageFrom="path/Component.tsx"
It also it may be that your "test" cmd you are running from package.json is obscuring the additional arguments, try directly calling jest from modules to see if thats the case.
This worked to me with create-react-app from windows cmd:
npx react-scripts test src/components/common/__test__/Dropdown.test.tsx --coverage --collectCoverageFrom=src/components/common/Dropdown.tsx

Running js tests - getting "Cannot use import statement outside of a module"

I added the type: module but that didn't help.
I am trying to run mocha or jest tests that use import and export for the source files.
The existing questions about this have specifics that are different from mine and I also find them confusing to follow for someone with my specific situation, especially since I have developed a specific answer with details not relevant to the existing questions, but relevant to other people in my situation.
In the past, you could not use ES modules (i.e. import/export) in Node without transpiling your code using Babel. However, support for ES modules in Node is now a reality, and both Jest and Mocha have also recently added support for using ES modules natively.
It takes more than just adding "type": "module" to your package.json, however.
Steps for using native ES Modules in Jest
As already mentioned, add "type": "module" to your package.json
Install either jest-environment-node or jest-environment-jsdom-sixteen to your development dependencies. For example:
$ npm i -D jest-environment-node
Update the Jest configuration in package.json and add the testEnvironment setting. For example:
"jest": {
"testEnvironment": "jest-environment-jsdom-node"
}
If you are using a version of Node earlier than 13.2, then you will need to add two additional flags when running Node: --experimental-modules and experimental-vm-modules. I use npx to execute the commands, although it's a little verbose:
$ npx --node-arg=--experimental-modules --node-arg=--experimental-vm-modules jest
This will run all your Jest tests using the appropriate Node flags. I'd recommend making this your test script in package.json if this is the way you go.
Now you should be able to use import/export without Babel!
One last important point: when using native ES modules in Node, you have to use the entire import path to your local modules, including the file extensions. For example:
import lib from "./my/lib.js"
Here is the Node documentation on native ES modules, if you want to read about this in more detail: https://nodejs.org/dist/latest-v14.x/docs/api/esm.html
I'd also recommend reading through this Github issue for more details on the Jest implementation of native ES modules: https://github.com/facebook/jest/issues/9430
Per the Jest documentation, if you make sure babel-jest is installed and supply your Babel configuration per the Babel documentation, in a config file or package.json e.g.:
.babelrc.json
{
"presets": [
"#babel/env"
]
}
Then babel-jest will pick it up automatically and you don't need to explicitly pre-build the files to test them. This also means you don't have to set flags on the command line when calling Babel.
Note that if you do want to explicitly pre-build, I'd recommend:
Using a pre<script> script rather than having multiple steps in one line; and
Re-using the build script so you don't have to make changes in two places.
In your case:
"scripts": {
"build": "babel src/ --out-dir lib",
"pretest": "npm run build",
"test": "jest lib/*.test.js"
}
You need to use a compiler and then use the compiled files when running tests.
Many of the references say to add type: module but don't say much more.
To be clear, the basic message:
SyntaxError: Cannot use import statement outside a module
is because you are using import/export and you are trying to run the files directly without compilation.
The mindshift here is getting used to editing the files in one directory and running the tests in another. Alternatively, some solutions offer "in'flight" compilation so this detail is essentially hidden and only the source files are used.
There are a few different approaches to doing this depending on specific needs. Here is one of the simplest approach I've found so far, using Babel for the compilation step:
Install babel npm install babel --save-dev
Add babel commands in package.json scripts, for example:
"scripts": {
"test": "babel src/ --out-dir lib --presets=#babel/env; jest lib/*.test.js",
"build": "babel src/ --out-dir lib --presets=#babel/env"
}, // this was for jest but you can use mocha, etc as needed
// Note that using preset this way eliminates the need for a specific .babel.config.json file
Now, if you run:
jest .
you get SyntaxError: Cannot use import statement outside a module, but if you run npm t you get
Successfully compiled 2 files with Babel.
PASS lib/app.test.js
All tests
✓ Canary test (2ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Going forward, just remember to:
Edit files in src/
Run tests in lib/

how to use testNamePattern of jest within package.json scripts field?

Honestly, jest of facebook has a bad document.
I want to use jest -t xxx to update my snapshots.
Here is my test, but no one works correctly.
jest -u -t='test.tsx'
jest -u -t 'test.tsx'
jest -u -t /test.tsx/
jest -u -t=/test.tsx/
I want to match and update snapshots test files which filename pattern like *.test.tsx.
How can I do that with jest testNamePattern?
First check jest --showConfig to see that you even have the option of --testNamePattern. I faced the same issue, and did not find this option in jest config.
So I changed my directory structure and used --testPathPattern option with regex. This works.
jest --testPathPattern='(tests)/spec/./snapshot-tests/.'

How can I use Mocha without removing Ava?

One of my co-workers added this Ava package to our setup, and it's done something I've never seen a Node package do before: interfere with other packages! Now when I try to run Mocha I get:
$ node_modules/mocha/bin/mocha test/
Test files must be run with the AVA CLI:
$ ava node_modules/mocha/bin/_mocha
I get that Ava would like to run my Mocha tests, but if I wanted that I'd run ava mocha not mocha. And because a co-worker is using it I can't simply uninstall the package.
Is there any way I can run plain Mocha tests on a machine with Ava installed?
One of the files in test/ imports ava and the imported code will recognise that it's not being run with the correct tooling and throw an error.
Might be worth subdividing your test/ directory to keep tests associated with their respective runners.
test/
ava/
SomeAvaTests.js
mocha/
SomeMochaTests.js
This way you can safely run mocha test/mocha/ and vice versa without worrying about treading on each other's toes.

Browserify command not found

Quick question, when I run browserify index.js -o app.js from mac terminal, I get command not found. I have done npm install -g browserify but still no luck. Any idea why I am getting this?
Thank you
It was easier for me to do a gist than to paste here:
https://gist.github.com/pertrai1/4ccf77e7b31cb5628b5d
Just install it in a global space like this if you need to run it from the command line.
npm install browserify -g
You may need to run
npm uninstall browserify -g fist just to be sure you don't have false aliases.
Add this to your ~/.bashrc or equivalent:
export PATH=$PATH:~/.npm-global/bin/
Then, to actually have this take effect in your terminal session, execute source ~/.bashrc.
At this point you can execute browserify, as well as potentially many other commands. Check out ~/.npm-global/bin/ to see what's become available.
I could not get browserify to work either.
Running ~/.npm/bin/browserify does work.
Other packages seem to run fine (phantomjs for instance).
A workaround fix seems to be adding alias browserify='~/.npm/bin/browserify' to your .bash_profile
It is an old post but I believe people are still facing the same problem, like me.
This was how I solved my problem:
<your project folder>/node_modules/browserify/bin/cmd.js main.js -o bundle.js
If you install locally npm install browserify, you can use this method to execute the browserify command.
node_modules/.bin/browserify
For example:
broweserify command example
Extra tips:
Add this command to your packages.js file:
...
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"bundle": "node_modules/.bin/browserify index.js > bundle.js"
},
Then everytime you want to bundle you file just hit npm run bundle
Hope it helps you guys out there..
If for some reason the browserify command has not been installed at all (can happen for example if you're running Homebrew on old unsupported Mac OS X versions), an alternative is to call it via node, for example:
export NODE_PATH=/usr/local/share/npm/lib/node_modules
node -e 'require("browserify")("input.js").bundle().pipe(fs.createWriteStream("output.js"))'
As a Mac user I had to add
export PATH=$PATH:/usr/local/Cellar/node/13.6.0/bin/
in ~.bash_profile
Why Cellar path i dont know.

Categories

Resources