Jest Unit Tests Fail When Test Directory Search Location Is Changed - jestjs

I am encountering an odd problem with jest: changing where jest looks for its test files appears to break the tests.
I've narrowed it down to a very small reproducable case.
This jest configuration, set in our package.json succeeds:
"jest": {
"testFileExtensions": ["jest"],
"testPathDirs": ["Views/Test"],
"scriptPreprocessor": "Views/Test/preprocessor.js",
"moduleFileExtensions": [ "js", "jsx" ],
"unmockedModulePathPatterns": [ "react" ]
}
Like so:
npm info it worked if it ends with ok
npm info using npm#2.2.0
npm info using node#v0.10.33
npm info pretest outfits#0.0.0
npm info test outfits#0.0.0
> outfits#0.0.0 test C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits
> jest
Using Jest CLI v0.2.2
Waiting on 2 tests...
PASS Views\Test\__tests__\Components\Outfit\Description\Description.jest (3.164s)
Waiting on 1 test...
PASS Views\Test\__tests__\Components\Outfit\GetTheLook\GetTheLook.jest (4.475s)
2 tests passed (2 total)
Run time: 5.339s
npm info posttest outfits#0.0.0
npm info ok
This jest configuration causes one of the two tests to fail. The only change is changing the root of where it looks for the __tests__ directory(ies).
"jest": {
"testFileExtensions": ["jest"],
"testPathDirs": ["Views"],
"scriptPreprocessor": "Views/Test/preprocessor.js",
"moduleFileExtensions": [ "js", "jsx" ],
"unmockedModulePathPatterns": [ "react" ]
}
With an oddball exception that looks like this (elided for brevity and reflowed for readability):
Using Jest CLI v0.2.2
Waiting on 2 tests...
PASS Views\Test\__tests__\Components\Outfit\Description\Description.jest (3.108s)
Waiting on 1 test...
FAIL Views\Test\__tests__\Components\Outfit\GetTheLook\GetTheLook.jest (3.233s)
● Get the look to › it encountered a declaration exception
- TypeError:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\flux.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\core\actions.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\util\useGlobal.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\util\object\getDeepProperty.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\util\object\result.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\node_modules\lodash-node\compat\object\result.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\node_modules\lodash-node\compat\lang\isFunction.js:
C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\node_modules\lodash-node\compat\lang\isNative.js:
Cannot call method 'replace' of undefined
at C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\node_modules\lodash-node\compat\lang\isNative.js:27:4
at Object.runContentWithLocalBindings (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\lib\utils.js:357:17)
at Loader._execModule (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\HasteModuleLoader\HasteModuleLoader.js:245:9)
at Loader.requireModule (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\HasteModuleLoader\HasteModuleLoader.js:900:12)
at Loader._generateMock (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\HasteModuleLoader\HasteModuleLoader.js:276:30)
at Loader.requireMock (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\HasteModuleLoader\HasteModuleLoader.js:796:43)
at Loader.requireModuleOrMock (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\src\HasteModuleLoader\HasteModuleLoader.js:919:17)
at C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\nord\node_modules\lodash-node\compat\lang\isFunction.js:2:16
...
at Suite.<anonymous> (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\Views\Test\__tests__\Components\Outfit\GetTheLook\GetTheLook.jest:5:13)
at env.describe_ (<anonymous>:40:25)
at env.describe (<anonymous>:27:19)
at describe (C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\node_modules\jest-cli\vendor\jasmine\jasmine-1.3.0.js:604:27)
at C:\tfs\Nordstrom.Outfits\Nordstrom.Outfits\Views\Test\__tests__\Components\Outfit\GetTheLook\GetTheLook.jest:4:1
...
at process._tickCallback (node.js:419:13)
1 test failed, 1 test passed (2 total)
Run time: 4.108s
npm info outfits#0.0.0 Failed to exec test script
npm ERR! Test failed. See above for more details.
Our source tree (also elided for brevity) looks like this:
<rootDir>/
|
+- package.json
|
+-node_modules/
| |
| +-gulp/
| +-jest/
| +-react
| +-...
|
+-Views/
|
+-Components/
| |
| +-Description/Description.jsx
| +-GetTheLook/GetTheLook.jsx
|
+-Test/
|
+- preprocessor.js
|
+- __tests__/
|
+-Components/
|
+-Outfit/
|
+-Description/Description.jest
+-GetTheLook/GetTheLook.jest

Related

Code coverage for integration test by jest and nyc always return 0% for statements and lines

I'm trying to do code coverage for our Jest integration tests.
The tests directory is inside some sub-directory inside the server project with standalone package.json and configurations.
The services and libs that need to cover are located in the main project root directory, that mean outside the tests sub-directory.
When I've tried to it by nyc is able to include the required directories outside the tests dir but no real coverage are return in the report.
When I've tried to id by the --coverage flag in Jest, It's not able to access outside the tests dir, even when adding rootDir option inside the configuration file, it just make a mess in the project.
I've also tried to execute nyc together with the api-gateway launching and together with the services launching but it didn't change the results as well.
The project architecture is something like the following -->
server-project root
.nyc_output
_coverage_
services
libs
src
api-gateway
test
- src
- integration-tests
- test.ts
- ...
- jest.config.ts
- jest-integration.config.ts
- package.json
package.json
Related versions:
Node v14.18.1
npm 6.14.15
pnpm 6.9.1
"istanbul-reports": "^3.1.5",
"jest": "^26.6.3",
"#types/jest": "^26.0.18",
"#types/node": "13.7.1",
"babel-plugin-istanbul": "^6.1.1",
"nyc": "^15.1.0",
"ts-jest": "^26.4.4",
"ts-node": "^9.1.1",
"typescript": "^4.1.2"
The script below contains nyc together with jest - non of them work as expected:
"test:integration:coverage": "nyc --cwd='../' --exclude-after-remapjest=false --reporter=lcov --reporter=text pnpm run test:integration -- --coverage --collectCoverageFrom='./../services/**/src/*.ts'",
It's located inside test/package.json and launchd by pnpm
nyc configuration inside package.json (project root) -->
"nyc": {
"extends": "#istanbuljs/nyc-config-typescript",
"require": "#babel/register",
"check-coverage": true,
"all": true,
"cache": true,
"sourceMap": false,
"instrument": true,
"lines": 90,
"branches": 90,
"functions": 90,
"statements": 90,
"reporter": [
"text-summary",
"lcov",
"text"
],
"report-dir": "coverage",
"include": [
"services/**/src/*.ts",
"api-gateway/src/*.ts",
"libs/**/src/*.ts"
],
"exclude": [
"**/test/**",
"**/*.d.ts"
],
"extension": [
".ts",
".tsx"
],
"temp-dir": ".nyc_output",
"excludeNodeModules": true,
"source-map": true,
"produce-source-map": true
}
Jest configuration iside test/jest-integration.config.ts (extends to the main jest.config.ts file) -->
// eslint-disable-next-line #typescript-eslint/no-var-requires
const baseConfig = require('./jest.config');
const base = '**/integration-tests/services';
const setupDir = './src/tests/integration-tests/setup';
module.exports = {
...baseConfig,
testMatch: [
...[
'abtests/*.test.ts',
'moretests/*.test.ts',
],
globalSetup: `${setupDir}/jest-integration-setup.ts`,
globalTeardown: `${setupDir}/jest-integration-teardown.ts`,
};
Output results:
at src/tests/integration-tests/services/abtests/abtest.test.ts:18:13
PASS src/tests/integration-tests/services/abtests/abtest.test.ts
abtests
✓ abtests params in me query (300 ms)
✓ override existing test (110 ms)
✓ create a new test with value (109 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 0 | 0 | 0 | 0 |
----------|---------|----------|---------|---------|-------------------
Failed to write coverage reports:
ERROR: TypeError: Cannot convert undefined or null to object
STACK: TypeError: Cannot convert undefined or null to object
at Function.getPrototypeOf (<anonymous>)
at Date (/Users/myname/repos/server-project/node_modules/.pnpm/jest-date-mock#1.0.8/node_modules/jest-date-mock/lib/mockDate.js:39:44)
at new HtmlReport (/Users/myname/repos/server-project/node_modules/.pnpm/istanbul-reports#3.0.2/node_modules/istanbul-reports/lib/html/index.js:260:21)
at new LcovReport (/Users/myname/repos/server-project/node_modules/.pnpm/istanbul-reports#3.0.2/node_modules/istanbul-reports/lib/lcov/index.js:14:21)
at Object.create (/Users/myname/repos/server-project/node_modules/.pnpm/istanbul-reports#3.0.2/node_modules/istanbul-reports/index.js:22:16)
at /Users/myname/repos/server-project/node_modules/.pnpm/#jest+reporters#26.6.2/node_modules/#jest/reporters/build/CoverageReporter.js:248:20
at Array.forEach (<anonymous>)
at CoverageReporter.onRunComplete (/Users/myname/repos/server-project/node_modules/.pnpm/#jest+reporters#26.6.2/node_modules/#jest/reporters/build/CoverageReporter.js:240:25)
at ReporterDispatcher.onRunComplete (/Users/myname/repos/server-project/node_modules/.pnpm/#jest+core#26.6.3/node_modules/#jest/core/build/ReporterDispatcher.js:88:9)
at TestScheduler.scheduleTests (/Users/myname/repos/server-project/node_modules/.pnpm/#jest+core#26.6.3/node_modules/#jest/core/build/TestScheduler.js:350:5)
at runJest (/Users/myname/repos/server-project/node_modules/.pnpm/#jest+core#26.6.3/node_modules/#jest/core/build/runJest.js:376:19)
at _run10000 (/Users/myanme/repos/server-project/node_modules/.pnpm/#jest+core#26.6.3/node_modules/#jest/core/build/cli/index.js:416:7)
at runCLI (/Users/myname/repos/server-project/node_modules/.pnpm/#jest+core#26.6.3/node_modules/#jest/core/build/cli/index.js:271:3)
at Object.run (/Users/myname/repos/server-project/node_modules/.pnpm/jest-cli#26.6.3/node_modules/jest-cli/build/cli/index.js:163:37)
Test Suites: 2 passed, 2 total
Tests: 1 skipped, 4 passed, 5 total
Snapshots: 0 total
Time: 10.01 s
Ran all test suites.
📦 report is created on: /Users/myname/repos/server-project/test/html-report/report.html
ERROR: Coverage for lines (0%) does not meet global threshold (90%)
ERROR: Coverage for functions (0%) does not meet global threshold (90%)
ERROR: Coverage for branches (0%) does not meet global threshold (90%)
ERROR: Coverage for statements (0%) does not meet global threshold (90%)
-----------------------------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------------------------------|---------|----------|---------|---------|-------------------
All files | 0 | 0 | 0 | 0 |
api-gateway/src | 0 | 0 | 0 | 0 |
config.ts | 0 | 100 | 100 | 0 | 81
main.ts | 0 | 0 | 0 | 0 | 11-43
storage.ts | 0 | 0 | 0 | 0 | 6-19
libs/apollo-federation-tester/src | 0 | 0 | 0 | 0 |
index.ts | 0 | 0 | 0 | 0 | 17-85
Please your help!
Thanks.

SyntaxError: Unexpected token export with SPFx solution while running Jest

I am getting this error:
FAIL src\webparts\crud\__test__\CrudWebPart.test.tsx
● Test suite failed to run
C:\Users\admin\Desktop\github\crud-simple-test\node_modules\#microsoft\sp-http\lib\index.js:12
export { default as HttpClient } from './httpClient/HttpClient';
^^^^^^
SyntaxError: Unexpected token export
54 |
55 | async postTodo() {
> 56 | const value = await this.addItem(this.state.todo);
57 | const action = postTodoCreator(value);
58 | store.dispatch(action)
59 | }
at ScriptTransformer._transformAndBuildScript (node_modules/jest/node_modules/jest-runtime/build/script_transformer.js:316:17)
at Object.<anonymous> (src/webparts/crud/components/Todolist/Todolist.tsx:56:68)
at Object.<anonymous> (src/webparts/crud/components/Crud.tsx:17:70)
console.log src\webparts\crud\components\Store\reducers.ts:27
action type ##redux/INITb.1.9.m.y.8 is not found
Handlebars: Access has been denied to resolve the property "statements" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Handlebars: Access has been denied to resolve the property "branches" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Handlebars: Access has been denied to resolve the property "functions" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
Handlebars: Access has been denied to resolve the property "lines" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | Unknown | Unknown | Unknown | Unknown | |
----------|----------|----------|----------|----------|-------------------|
Jest: Coverage data for global was not found.
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 8.522s
Ran all test suites.
testResultsProcessor support is deprecated. Please use jest reporter. See https://github.com/jest-community/jest-junit#usage:
{
"reporters": [
"jest-junit"
]
}
npm ERR! Test failed. See above for more details.
This is strange, because after doing some research I changed my config:
"transformIgnorePatterns": [
"/node_modules/(?!#microsoft/sp-core-library|sp-dialog|sp-http)"
],
Yet this little fix doesn't seem to cut it even though this seems to be what people did to fix similar issues. Is this a Typescript problem or is it something else? And how do I make sure the Typescript compiler does its job?
In my case, I configured package.json so jest ignores all these:
"transformIgnorePatterns": [ "node_modules/(?!(#microsoft/sp-dialog|#microsoft/office-ui-fabric-react-bundle|#microsoft/sp-diagnostics|#microsoft/sp-core-library|#microsoft/sp-http|#microsoft/sp-page-context|#microsoft/sp-dynamic-data|#pnp/sp|#pnp/common|#pnp/odata|#pnp))" ],

how to fix 'error from lcovParse: ' 'Failed to parse string'? on circleICI v2.0 using coveralls with mocha

circleCI fails when it tries to run this command:
#!/bin/bash --login
cat ./coverage/coverage.json | ./node_modules/.bin/adana --format lcov | ./node_modules/coveralls/bin/coveralls.js
[error] "2019-02-20T20:22:50.695Z" 'error from lcovParse: ' 'Failed to parse string'
[error] "2019-02-20T20:22:50.697Z" 'input: ' '\n'
[error] "2019-02-20T20:22:50.697Z" 'error from convertLcovToCoveralls'
/home/ubuntu/Band-of-Coders/uber-auth/node_modules/coveralls/bin/coveralls.js:18
throw err;
^
Failed to parse string
Exited with code 1
this it is how I run my tests:
./node_modules/.bin/_mocha -r test/helper/chai.js -r adana-dump --compilers js:babel-core/register -R spec --recursive --slow 100 test/spec/**/*.spec.js
In my .circleci/config.yml, I have:
- run: npm test
- run: npm install coveralls
- run: cat ./coverage/coverage.json | ./node_modules/.bin/adana --format lcov | ./node_modules/coveralls/bin/coveralls.js
any thoughts about why this is happening?
I really appreciate any help
You might need to make use of nyc with babel-plugin-istanbul or plain istanbul to generate the coverage data first before you run your coverage reporting script. Otherwise, there'd be no data available to generate a report.
I've used nyc with babel-plugin-istanbul before and got expected results.
"test": "NODE_ENV=test nyc ./node_modules/.bin/_mocha <your-test-matching-wildcard-here>",
"coveralls": "NODE_ENV=test nyc report --reporter=text-lcov | coveralls"
You'll also need to have some configuration in your .nycrc:
{
"reporter" : ["text", "text-summary", "lcov", "html"],
"include" : ["<your-include-wildcard>"],
"exclude" : ["<your-exclude-wildcard>"],
"require" : ["#babel/register"],
"sourceMap" : false,
"instrument" : false,
"all" : true
}
Run test script first then coveralls.

Use Jest and spread operator without babel?

Is it possible to use the spread operator in code with Jest and without babel if the node engine is 8+?
I am dropping support for Node.js <8 in my app and assumed I could remove all babel dependencies and transpiling from package.json, however npm run jest fails immediately with these types of errors:
FAIL test/workers/repository/onboarding.spec.js
● Test suite failed to run
/Users/me/project/lib/workers/repository/onboarding.js: Unexpected token (13:17)
11 |
12 | async function createOnboardingBranch(inputConfig) {
> 13 | let config = { ...inputConfig };
| ^
Is there any way to get Jest to work without needing to add back all the babel dependencies and configuration?
Node.js version: 8.9.0
Jest version: 20.0.4
jest config in package.json:
"jest": {
"cacheDirectory": ".cache/jest",
"coverageDirectory": "./coverage",
"collectCoverage": true,
"collectCoverageFrom": [
"lib/**/*.js"
],
"coverageReporters": [
"json",
"lcov",
"text-summary"
],
"setupTestFrameworkScriptFile": "./test/chai.js"
},
Edit:
I have been able to narrow my babel configuration down to just one plugin: babel-plugin-transform-object-rest-spread and configure babel in package.json like so:
"babel": {
"plugins": [
"transform-object-rest-spread"
]
},
Taking this out or attempting to use babel-preset env causes Jest to fail on the spread operator again.

What don't I get about babel with istanbul?

I'm trying to add code coverage to an existing library that transpiles from ES2015. I seem to be doing everything right. My makefile reads
test: .FORCE
export NODE_ENV=test
babel *.js --out-dir lib
nyc mocha
And my babelrc reads
{
"presets": ["es2015"],
"sourceMaps": true,
"env": {
"test": { "plugins": ["istanbul"] }
}
}
while my package.json includes
"nyc": {
"include": [
"**/*.js"
],
"require": [
"babel-register"
],
"sourceMap": false,
"instrument": false
}
And yet, after my tests run, the output simply reads:
----------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
----------|----------|----------|----------|----------|----------------|
All files | Unknown | Unknown | Unknown | Unknown | |
----------|----------|----------|----------|----------|----------------|
I've tried what feels like every combination of babel-node, babel-istanbul, and nyc, with various include directives, and I've never gotten it to so much as report a file with 0% coverage, even when using --include-all-sources. What gives? What am I missing?
You need to instrument the code that is getting transpiled. Use this babel plugin: https://github.com/istanbuljs/babel-plugin-istanbul
The package you're using babel-istanbul is a drop-in package meant to be used in replacement of babel.

Resources