Jest regex to match certain test files - jestjs

I have integration tests under dir src/test/integration. All files are named like so: foo.integration.js.
Running Jest:
jest ".*\\.integration\\.js"
produces this error:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In /Users/dangruszczyk/workspace/cef/lambda-workflow
7 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 1 match
testPathIgnorePatterns: /node_modules/ - 7 matches
testRegex: - 0 matches
Pattern: .*\.integration\.js - 0 matches
Surely this regex should match src/test/integration/foo.integration.js (https://regex101.com/r/T3WJwd/1/). Any clue why it does not?

The problem is that Jest is still applying the testMatch, i.e. you're filtering within the files it has already determined to be test files, and src/test/integration/foo.integration.js matches neither **/__tests__/**/*.[jt]s?(x) nor **/?(*.)+(spec|test).[tj]s?(x)*.
To run those files, you're probably best off setting the testMatch instead:
jest --testMatch='**/*.integration.js'
This doesn't seem to be a documented part of the CLI, but works fine (for now!) in practice.
* Interestingly, neither does path/to/my-test.js, the example shown in the docs...

I was doing the same thing, but in the end it felt more natural to restructure.
By using .test.js you can easily run all tests or selectively filter sub-types.
example.integration.test.js
example.unit.test.js
"scripts": {
"test-all": "jest",
"unit-test": "jest \"--testPathPattern='.+\\.unit\\.test\\.js$'\"",
"integration-test": "jest \"--testPathPattern='.+\\.integration\\.test\\.js$'\""
},
As others have said, jest expects test files to end .test.js or .spec.js.

Related

Jest: Automatically collect coverage from tested files

In my application, while developing, I run:
npm run test src/components/component.test.tsx
This runs the specific test suite for the component I'm working on.
On top of that, I can then change it to:
npm run test src/components/component.test.tsx -- --coverage --coverageReporters=text-summary --collectCoverageFrom=src/components/component.tsx
Which will print a coverage report for that specific file once the tests have been run.
As you can see this is extremely wordy and only gets worse if I want to test two or three files at the same time.
Is there any way to automate collectCoverageFrom to collect coverage from the files that have been tested (not from all files in the project) so that I don't have to type it out manually every single time?
Just omit the "collectCoverageFrom" (or explicitly set it to an empty glob if you're overriding the config file).
Jest will then only collect coverage from files that are used during the test run.
Set it up in your jest configuration file.
your npm script will look like jest -c path/to/jest.config.js
jest.config.js will look like
module.exports = {
collectCoverage: true,
// The directory where Jest should output its coverage files
coverageDirectory: "./coverage",
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
coverageReporters: ["html", "text", "cobertura"],
}
If you do jest --init it will help you build a new config file
Side note: You may want to set up a jest wildcard so you don't need to individually write down every file you want to test.

Can't target test directory with jest testMatch glob pattern

Let's say that I have a project structure like below:
src/index.js
src/test/foo.js
test/integration/src/index.test.js
test/unit/src/index.test.js
jest.config.json
In jest.config.json I have my testMatch
{
"testMatch": [
"test/**"
]
}
When I run jest with --config jest.config.json it matches with 0 file.
testMatch: test/** - 0 matches
testPathIgnorePatterns: /node_modules/ - 5 matches
testRegex: - 0 matches
Pattern: - 0 matches
I thought it might be related with some incorrect rootDir since testMatch is relative to that. I run jest in debug mode to see my root and it seems it's correct. It shows my project directory. (where jest.config.json exists)
When I change my testMatch to **/test/** it can detect my tests in test/ directory but that's not what I want because then it also matches with src/test/ directory.
Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?
Why it cannot detect my tests in test/ directory? Is my glob pattern incorrect?
Jest's glob implementation has been going through some issues as of late. Under the hood Jest uses micromatch, but why it is getting hung up on relative path globs is unclear.
There are a couple things you can try in your Jest config:
Include the <rootDir> string token directly in your testMatch glob like testMatch: ['<rootDir>/test/**'].
Follow the globstar example more closely from the Jest testMatch documentation, paying attention to the note about glob order:
Note: Each glob pattern is applied in the order they are specified in the config. (For example ["!/fixtures/", "/tests//.js"] will not exclude fixtures because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after /tests//.js.)
testMatch: [
'**/test/**',
'!**/src/**'
]

Jest ignore Cypress test

I have a create-react-app app and used to use jest for testing but I'm slowly migrating to cypress.
The thing is, now when I run my jest tests, it includes my cypress tests and gives an error
ReferenceError: Cypress is not defined
How can I make it that my jest (naming convention *.test.js) test ignore my cypress test (which are usually called *.spec.js)?
You should use testPathIgnorePatterns in your jest config.
An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped.
According to Jest config docs
jest.config.js
module.exports = {
// Your normal jest config settings
testPathIgnorePatterns: ["<rootDir>/cypress/"],
}
In your jest/config.js or wherever you have your jest config (could be package), add the following to replace the default regex to find tests from
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$"
to:
"testRegex": "(/__tests__/.*|(\\.|/)(test))\\.[jt]sx?$"

Is there a good report for jest test case?

I am using jest to test my reactjs application. It works fine but jest doesn't give me a good report about test case results. The output of jest shows each test suite followed by its output. I have more than 50 test suites and it is hard for me to scroll up to check each failed test cases. Is there a brief jest report which printing a brief summary about the whole test cases?
below is my jest.conf file:
{
"testRegex": "/tests/.*\\.test\\.jsx?$",
"testEnvironment": "node",
"roots": ["./src"],
"coverageReporters": ["text-summary", "html"]
}
There is also a JEST HTML Reporter module which you might find useful.
It's configurable to specify what level of detail you want to show in the test report for failures
https://www.npmjs.com/package/jest-html-reporter
You can run jest with the --coverage flag.
If you want something different than the default reporters, you have to set them in your jest config file.
jest.json
{
"coverageReporters": ["text-summary", "html"]
}
text-summary gives you a short summary beneath all tests that tells you how many suites/tests are successful/failed.
html gives you a some html pages that you can browse through to see exactly what got tested.
CLI
$ ./node_modules/.bin/jest --config ./path/to/jest.json --coverage
You might want to adjust which files are covered etc.
See all coverage options in the jest docs.
https://github.com/jest-community/awesome-jest#reporters contains a list of other reporters. jest-stare will let you filter off passing tests so you can just see the ones that failed.
Use Istanbul to generate Reports
In the Script section of the Package.json just add :
"scripts": {
"test": "jest",
"test-coverage": "jest --coverage",
}
Save the project and run below command:
Yarn test : For Terminal Coverage
Yarn test-coverage for Report Generation.Find HTML report in Coverage > Icov-report >index.html
If you can use a web-based reporter try Tesults - a reporter for Jest is available to help with integration: https://www.npmjs.com/package/jest-tesults-reporter.
You main issue, with respect to navigating test suites is handled well. I should add a disclaimer that I work at Tesults, but on the other hand if this is for a very small team or it's open source it is free to use, just contact support.

Run "node test" as part of Visual Studio Team Services build task with results in "tests" tab

I have a project that contains tests that I am running with Mocha from the command line. I have set up a test script in my packages.json, which looks as follows:
"test": "mocha ./**/*.spec.js --reporter dot --require jsdom-global/register"
I have currently got a simple task set up in Visual Studio Team Services, which just runs the npm test command, this runs Mocha within a console and continues/fails the build depending on whether the tests pass.
What I'd like to be able to do is have the results of my tests populate the "tests" tab in the build definition after it's run. In the same way that I can get this tab populated if I'm running tests on C# code.
I've tried using Chutzpah for this, but it's overly complicated and seems to require that I jump through all sorts of hoops that mean changing my tests and writing long config files. I already have loads of tests written, so really don't want to have to do that. When it did finally discover any of my tests, it complained about require and other things related to Node modules.
Is what I'm asking for actually possible? Is there a simple way of achieving this that's compatible with running my tests in Node?
I've found a good way of doing it that requires no third-party adapter (eg. Chutzpah). It involves getting Mocha to output its report in an XML format, and setting up Visual Studio Team Services to publish the results in an extra step of the build definition.
I installed mocha-junit-reporter (https://www.npmjs.com/package/mocha-junit-reporter) and altered my test script to the following:
"test": "mocha ./temp/**/*.spec.js --reporter mocha-junit-reporter --require jsdom-global/register"
I then created a new step in my build definition using the "Publish Test Results" task. I set the result format to "JUnit" and added the correct path for the outputted test-results.xml file created by the reporter.
It is worth noting that although Mocha comes with an "XUnit" reporter, this format appears to not work correctly with VSTS even though it's listed as an option.
The results of npm test now show up in the "tests" tab alongside any other tests from MSTest etc.
I'm using karma and got this to work in the same way as #dylan-parry suggested. Some excepts below in case it helps others:
package.json
"scripts": {
"test": "cross-env NODE_ENV=test karma start"
}
karma.conf.js
const webpackCfg = require('./webpack.config')('test');
module.exports = function karmaConfig(config) {
config.set({
reporters: ['mocha', 'coverage', 'junit'],
junitReporter: {
outputDir: 'coverage',
outputFile: 'junit-result.xml',
useBrowserName: false
}
})
...
TFS
It may also be worth adding I'm using branch policies on my git branch to prevent PR's being merged if the tests fail, info via this link:
https://www.visualstudio.com/en-us/docs/git/branch-policies
Here's the output in TFS:
Next step is to get the coverage working too!

Resources