SyntaxError: Unexpected token export with SPFx solution while running Jest - jestjs

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))" ],

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.

Turborepo: SyntaxError: Cannot use import statement outside a module

This is the complete error I get:
cache bypass, force executing 35a9a396ec0cc67c
$ jest --verbose
FAIL __test__/Krebit.test.ts
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/andres/Work/krebit-work/krebit/node_modules/#glazed/datamodel/dist/index.js:41
import { TileLoader } from '#glazed/tile-loader';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import { ethers } from 'ethers';
2 | import { CeramicClient } from '#ceramicnetwork/http-client';
> 3 | import { DataModel } from '#glazed/datamodel';
| ^
4 | import { DIDDataStore } from '#glazed/did-datastore';
5 |
6 | // DID-session
at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/lib/ceramic.ts:3:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.909 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
ERROR: command finished with error: command (packages/reputation-passport) yarn run test exited (1)
I have already installed the following packages and added this config:
Packages:
#types/jest: ^28.1.6
jest: ^28.1.3
ts-jest: ^28.0.7
Configuration for jest:
module.exports = {
testEnvironment: 'node',
preset: 'ts-jest',
testMatch: null,
testRegex: '/__test__/.*\\.test\\.(js|ts)$',
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/out/'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
clearMocks: true,
globals: {
'ts-jest': {
tsconfig: '<rootDir>/__test__/tsconfig.json',
diagnostics: false
}
}
};
The test I'm implementing is as simple as:
import { ethers } from 'ethers';
import Krebit from '../src';
describe('Krebit Class', () => {
let wallet: ethers.Wallet;
let ethProvider: ethers.providers.Provider;
beforeAll(async () => {
ethProvider = Krebit.lib.ethereum.getProvider();
const pKey = ethers.Wallet.createRandom();
wallet = new ethers.Wallet(pKey, ethProvider);
});
test('The user should be able to connect with her Wallet, EthProvider, and Address', async () => {
console.log(wallet, ethProvider);
});
});
So, I guess the problem comes from the line: ethProvider = Krebit.lib.ethereum.getProvider();, which is importing the package I want to test... If someone needs to read this code, I can share it too...

Jest testcase failed due to unexpected token while parsing a flow type in react-native

I am trying to setup jest with my react-native app. I created a simple test case and while running npm test, I get the following error
FAIL __tests__/actionsSpecs.js
● Test suite failed to run
/Users/abc/Projects/MyApp/node_modules/react-native/Libraries/Renderer/src/renderers/shared/hooks/ReactHostOperationHistoryHook.js: Unexpected token (20:4)
18 | & {instanceID: DebugID}
19 | & (
> 20 | | {type: 'mount', payload: string}
| ^
21 | | {type: 'insert child', payload: {toIndex: number, content: string}}
22 | | {type: 'move child', payload: {fromIndex: number, toIndex: number}}
23 | | {type: 'replace children', payload: string}
Basically, it is failing on a flow type declaration. I have tried using flow babel preset and transform-flow-strip-types but that didn't help.
Below is my jest configuration in package.json
"jest": {
"preset": "react-native",
"setupFiles": [
"./setup.js"
],
"transformIgnorePatterns": [ "node_modules/(?!react-native)" ]
}
This is the .babelrc file
{
"presets": ["react-native", "flow"]
}
It looks like the flow preset didn't get rid of the flow types during transpilation but I don't know how to get it to work now.
Please let me know if you know what is wrong.
You need more than just presets, you also need a transform that strips flowtypes. Usually this is done with with the babel plugin babel-plugin-transform-flow-strip-types.
Your .babelrc file should look something like this:
{
"presets": [
"react-native"
],
"plugins": [
"transform-flow-strip-types"
]
}
Edit: Another possibility is that your flow syntax is incorrect, and the transform doesn't know how to handle it. It looks to me from the snippet you've pasted that there's an extra | preceding the object definition on line 20. Does removing that change the output at all?

NodeJs request modules runtime Error: ./..../tough-cookie/package.json

When I install NodeJs module, there is a bug in the running.
request module is the latest version:
npm install request
stream.js:74
throw er; // Unhandled stream error in pipe.
^
Error: ./~/request/~/tough-cookie/package.json
Module parse failed: /Users/DongYao/Develop/proj-1/weicang_c/node_modules/request/node_modules/tough-cookie/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "author": {
| "name": "Jeremy Stashewsky",
| "email": "jstashewsky#salesforce.com"
# ./~/request/~/tough-cookie/lib/cookie.js 38:14-40./~/request/~/mime-types/~/mime-db/db.json
Module parse failed: /Users/DongYao/Develop/proj-1/weicang_c/node_modules/request/node_modules/mime-types/node_modules/mime-db/db.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "application/1d-interleaved-parityfec": {
| "source": "iana"
| },
==================
and more.........
Please help me.

Jest Unit Tests Fail When Test Directory Search Location Is Changed

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

Resources