Jest / Puppeteer complains that 'export' isn't valid syntax [duplicate] - javascript

I used to solve similar errors while I was using Jest with only JavaScript, but currently I'm not able to do so with Typescript.
All my tests were running fine until I installed Puppeteer which requires #types/jest-environment-puppeteer, #types/puppeteer and #types/expect-puppeteer.
After installing them, puppeteer tests are running perfectly, but other tests started to fail with below error.
D:\...\api\node_modules\uuid\dist\esm-browser\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { default as v1 } from './v1.js';
^^^^^^
SyntaxError: Unexpected token 'export'
at Runtime.createScriptFromCode (../node_modules/jest-runtime/build/index.js:1796:14)
at Object.require (../node_modules/#nestjs/common/decorators/core/injectable.decorator.js:4:16)
WHAT I DID?
allowJs: true on tsconfig.json and set the transformIgnorePatterns on jest configs. So that jest can compile files from node_modules/
After that this error stopped but test failed for another strange reason.
And worse is that test start time have increased too much.
So I left allowJs as in original setup and updated jest config from
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
to
"transform": {
"^.+\\.(t)s$": "ts-jest"
}
So currently ts-jest doesnt compile js files. But I think I am not able to make babel pick the transformation for js files. These are my jest configs:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t)s$": "ts-jest",
"^.+\\.(js|jsx)$": "babel-jest"
},
"transformIgnorePatterns": ["<rootDir>/node_modules/.+.(js|jsx)$"]
}

Thanks to this reply:
https://stackoverflow.com/a/54117206/15741905
I started googling for similar fixes and ended up here:
https://github.com/uuidjs/uuid/issues/451
And this solved my problem: https://github.com/uuidjs/uuid/issues/451#issuecomment-1112328417
// jest.config.js
{
//................
moduleNameMapper: {
// Force module uuid to resolve with the CJS entry point, because Jest does not support package.json.exports. See https://github.com/uuidjs/uuid/issues/451
"uuid": require.resolve('uuid'),
}
}
Tough I would still be happy if there is solution to this by using jest-babel.
Because I had to carry jest configs from package.json to a seperate .js file.
Edit:
According to this github issue compatibility issue has been solved with the latest release of the uuid library.

Simply adding moduleNameMapper:{"^uuid$": "uuid"} into my jest.config.js fixed the issue for me:
transient dependency uuid: ^8.3.2
jest: 28.1.3
angular: 14.0.1

Upgrade to uuidv4() version 9.0.0 ("uuid": "^9.0.0") now fixes the the issue. See comment from SimenB: https://github.com/uuidjs/uuid/issues/451#issuecomment-1377099565
I tried the answer above initially, adding moduleNameMapper:{"^uuid$": "uuid"} into my jest.config.js, which fixed the issue for me. Then I followed the link (above) to read more and I saw that it has been fixed in "uuid": "^9.0.0".
So I took out the fix, installed latest uuidv4() at version 9.0.0, (package link below) and it started working fine again. No more errors and tests are running fine, again. https://www.npmjs.com/package/uuid
My React App started having the issues after updating "jest": "26.0.1" to "jest": "29.4.1", "environment-jsdom-fifteen": "1.0.2" to "jest-environment-jsdom": "29.4.1". along with other updates "ts-jest": "26.5.6" to "ts-jest": "^29.0.5". However, as mentioned above, upgrading to uuid version 9.0.0 has fixed it.

Date : 2/15/2023
Jest Version : "#types/jest": "^29.4.0",
UUID Version : "uuid": "^9.0.0"
using the jest.config.ts will generate an error that says
Multiple configurations found
here's how you can override that
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../src/App';
import {v4 as uuidv4} from 'uuid';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
jest.mock('uuid', () => {
return {
v4: jest.fn(() => 1)
}
})
Hoping this will solve other peoples error if the correct answer is not working for you :).

adding this to the package.json file solved it for me:
"devDependencies": {
....
},
"browser": {
"uuid": "./node_modules/uuid/dist/esm-browser/index.js"
}

Related

Jest fails when rendering React component with 'No element indexed by'

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:
When I run any test that renders a component, it spits out the error No element indexed by 7.
Here is the full stack trace:
FAIL __tests__/App-test.tsx
● Test suite failed to run
No element indexed by 7
at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
at Function.write (node_modules/#jest/console/build/BufferedConsole.js:101:7)
at console._log (node_modules/#jest/console/build/BufferedConsole.js:117:21)
at console.error (node_modules/#jest/console/build/BufferedConsole.js:161:10)
This same error occurs with any component I attempt to render.
Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest #babel/core #babel/preset-env) and setting "coverageProvider" in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It's definitely possible that I configured something else wrong. Here are some code snippets which may be of use:
App-test.tsx
/**
* #format
*/
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
package.json
// ...
"jest": {
"preset": "react-native",
"coverageProvider": "babel",
"transformIgnorePatterns": [
"node_modules/(?!(react-native|#react-native|react-native-video|react-native-reanimated|#miblanchard/react-native-slider|react-native-gesture-handler)/)"
],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
babel.config.js
module.exports = {
presets: [
'module:metro-react-native-babel-preset',
['#babel/preset-typescript', {allowDeclareFields: true}],
],
plugins: [
"react-native-reanimated/plugin",
],
};
As an additional note, I have tried adding #babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.
Edited to note that these tests fail regardless of whether or not the --coverage argument is applied
In the end, I solved my error by uninstalling node_modules, re-running npm install --save-dev babel-jest #babel/core #babel/preset-env and adding
"setupFiles": [
"./node_modules/react-native-gesture-handler/jestSetup.js",
// ...
]
to my package.json

Module not found: Error: Can't resolve 'crypto'

I am getting the following list of errors when I run ng serve.
My package JSON is as follows:
{ "name": "ProName", "version": "0.0.0", "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e" }, "private": true, "dependencies": {
"#angular-devkit/build-angular": "~0.12.0",
"#angular/animations": "5.2.10",
"#angular/common": "5.2.10",
"#angular/compiler": "5.2.10",
"#angular/compiler-cli": "5.2.10",
"#angular/core": "5.2.10",
"#angular/forms": "5.2.10",
"#angular/platform-browser": "5.2.10",
"#angular/platform-browser-dynamic": "5.2.10",
"#angular/router": "5.2.10",
"#types/dotenv": "^4.0.3",
"#types/errorhandler": "0.0.32",
"#types/express": "^4.16.0",
"#types/node": "^10.5.1",
"apostille-library": "^7.1.0",
"core-js": "^2.5.4",
"dotenv": "^6.0.0",
"errorhandler": "^1.5.0",
"express": "^4.16.0",
"nem2-sdk": "^0.9.7",
"rxjs": "~6.3.3",
"stream": "0.0.2",
"tslib": "^1.9.0",
"typescript": "^2.9.2",
"zone.js": "~0.8.26" } }
The error I get :
ERROR in ./node_modules/aws-sign2/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/aws-sign2' ERROR in
./node_modules/aws4/aws4.js Module not found: Error: Can't resolve
'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws4'
ERROR in ./node_modules/ecc-jsbn/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/ecc-jsbn' ERROR in
./node_modules/http-signature/lib/verify.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/http-signature/lib/signer.js Module not found:
Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/nem-sdk/build/external/nacl-fast.js Module not
found: Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/nem-sdk/build/external'
ERROR in ./node_modules/nem-sdk/node_modules/aws-sign2/index.js
I ran into a similar issue lately while trying to use another library (tiff.js) in a small project I was experimenting with.
The way I got around this was to add the following to my package.json file, right after the devDependencies section.
"devDependencies": {
...
},
"browser": {
"crypto": false
}
This didn't seem to have any adverse effect when trying to use the library in the application.
Adding this setting in tsconfig.json file under that project resolve this warning
"compilerOptions": {
"baseUrl": "./",
"paths": {
"crypto": [
"node_modules/crypto-js"
]
}
I like R. Richards's answer, but I thought it would be useful to provide some more information.
This is a known issue with Angular, and the Angular CLI dev team seems to think it's a feature rather than a bug. I, as well as other developers in this issue thread, disagree. Contributors to that thread provided several workaround fixes, but my project didn't compile successfully until I implemented R. Richards' solution. I didn't revert the previous changes, though, so tacnoman's and GrandSchtroumpf's fixes may be of use to others.
Some, like clovis1122 here and others in that issue thread, have questioned why a web app would need access to these libraries and why the necessary tasks can't be completed on the server side instead. I can't speak for everyone, but my use case is that, when authenticating a user account, Strapi responds with a JSON Web Token string that must be decoded by the client. Since the necessary library depends on crypto and stream, you won't be able to extract the JWT expiration time unless those dependencies are available.
In case anyone has trouble extrapolating from R. Richards' answer, you'll have to set to false any dependencies that are showing up in "can't resolve x" errors. For example, the critical part of my package.json is:
"browser": {
"crypto": false,
"stream": false
}
I thought I would expand on what Tarique Ahmed wrote in his answer.
I was using an npm module that had the following line in the code:
const crypto = require('crypto');
I couldn't add:
"browser": {
"crypto": false
}
to the package.json because the crypto package had to be part of the build.
It turns out that during the compilation process Angular seems to have decided to install the crypto-browserify package instead of crypto.
Adding the following to the tsconfig.json file instructs the build to use the crypto-browserify library every time that crypto is required. As you can see, I had the same issue for the stream package.
"paths": {
"crypto": [
"node_modules/crypto-browserify"
],
"stream": [
"node_modules/stream-browserify"
]
}
After having the same issue with Angular 11 and crypto-js 4 (and manually setting the path in tsconfig.json), I found rolling back crypto-js to version 3.1.9-1 fixed the issue. It seems a change made in version 4 caused the issue.
npm install crypto-js#3.1.9-1
Explained here in repo issues:
GitHub issue
If you upgraded to Webpack 5, you need to add this to your webpack config file:
resolve: {
fallback: { crypto: false },
},
aws-sign2 is a NodeJS package (and crypto is a NodeJS module), but it looks like you're dealing with a web application. It makes sense that the crypto module is not available in that environment.
Would it be possible to complete what you need to do server-side? Otherwise, you may need to look for another package.
For Laravel Inertia JS project, my solution was:
1- Add dependencies to package.json
"dependencies": {
"crypto-browserify": "3.12.0",
"crypto-random-string": "^3.3.0",
"stream": "^0.0.2"
}
2-In webpack.config.js:
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
},
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream'),
},
},
};
3-Install, build and run:
npm install && npm run watch
I have resolved my issue using below steps:
Add below to tsconfig.json to resolve crypto warning:
"paths": {
"crypto": [
"node_modules/crypto-js"
]
},
and add below to angular.json
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
],
...
}
My Error
In my Case the import { get } from "express/lib/response" is the culprit, which is automatically added by vs-code.
So, after removing it I solved my issue
When using #Laravel framework with Laravel Mix this is going to be more trick. I spend some hours on this NPM nightmare and found a solid solution.
So, in your webpack.mix.js you find the 'comment'
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
Now just below that comment add the following lines;
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.LoaderOptionsPlugin({
exports: {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
}
}
}
})
]
};
});
Now you can use Laravel Mix just like you would edit webpack.config.js ;)
Also; In package.json remove:
--no-progress --hide-modules
These are no longer valid for WebPack >= 5. Enjoy!
After a deep a research i found that the solution is very simple: replace
import * as CryptoJS from 'crypto-js'; with declare var CryptoJS;
Using direct import may not work with ES6 Enviornment..
This may help you.
$ npm i crypto-js#latest // For using latest version 4
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { secretKey } from './environments/environment';
/** Encryption */
const data = {key: 'Test Value'};
const ciphertext = AES.encrypt(JSON.stringify(data), secretKey).toString();
console.log('Encrypted Data', ciphertext);
/** Decryption */
const bytes = AES.decrypt(ciphertext, secretKey);
const decryptedData = JSON.parse(bytes.toString(Utf8));
console.log('Decrypted Data', decryptedData);
https://github.com/brix/crypto-js/issues/168#issuecomment-785617218
Add the option allowedCommonJsDependencies with literal "crypto-js" in a array, this in file angular.json:
"architect":
"build": {
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
]
},
}
}
This will disable all warnings, tested in Angular 11.
My problem was that I was trying to build to node and web using the same code, but is not possible to built to web while importing a WebSocket dependency, ws in my case
So the solution is by using a wrapper:
Install a wrapper, I will use isomorphic-ws because is made for ws
npm i --save isomorphic-ws
Remove const WebSocket = require('ws')
Replace with:
const WebSocket = require('isomorphic-ws')
I ended up going into
node_modules/react-scripts/config/webpack.config.js
and adding:
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
https: require.resolve("https-browserify"),
http: require.resolve("stream-http"),
url : require.resolve("url")
}
And now my react app builds with errors but no dependency issues. Ill update this when I get it building.
Add
npm install crypto-js
Or Add a specific version according to your project need
npm install crypto-js#4.0.0
Also, run the above commands in Window "run as administrator" or in Linux use sudo
Alot of answers already but still none of them works. In my case I see warning message
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }
comment from #stewii did helped me to resolved this.
There is now an ES modules version called "crypto-es". It clears these warnings. npmjs.com/package/crypto-es
After this I imported cryptoES
import CryptoES from 'crypto-es';
and remove the existing import of cryptoJs. Re-start the compile and Voila.. The warning message is gone.
I tried a lot of the solutions above but the final thing that worked for me was downloading the crypto-es package and adding, "type":"module" to package.json.
https://www.npmjs.com/package/crypto-es
I was facing same issue, Just run node patch.js and it worked. The issue is, browser doesn't allow server files to be run on browser. In case you need some of these, You can use node patch.js. If you don't want to run any server file on browser, you can simply apply above mentioned solution by #R.Richards. Might be helpful for someone..
In my case, the solution described by R.Richards doesn't work.
However, following several threads along this issue, I finally understood where to insert the recommendation provided in the warning message and solved this warning.
WARNING in ./node_modules/bcryptjs/dist/bcrypt.js 64:13-45
Module not found: Error: Can't resolve 'crypto' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\bcryptjs\dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
**If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }**
Differently from many contributors, I didn't want to install crypto-browserify as I don't need it (*), and I chose to add the fallback { "crypto": false }.
However I didn't know where to add this fallback. After reading several threads, I found it was in the webpack.config.js file, which is located in the directory node_modules/react_scripts/config.
Adding this fallback made the compilation succeed without any warning.
(*) PS : I once tried to add the following fallback { "crypto": require.resolve("crypto-browserify") }, but it led to generation of 7 errors, requiring other modules :
Failed to compile.
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/cipher-base/index.js 2:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/readable-stream/lib/_stream_readable.js 43:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/_stream_writable.js 65:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/internal/streams/buffer_list.js 63:15-32
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib\internal\streams'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/ripemd160/index.js 3:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\ripemd160'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safer-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
webpack compiled with 7 errors
I had this problem in ReactJS with create-react-app(facebook)
Solution:
First install the necessary packages "crypto-browserify"
Modify webpack.config.js in reactjs with create-react-app this file is inside:
node_modules/react-scripts/config/webpack.config.js
Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
}
}
}
}
Note: Is possible you need other packages how "stream-browserify" the steps are same. This solution works, but when the webpack project starts it shows warnings
Pd: I am not native speaker English, but I hope understand me.

"Unexpected token import" when testing Angular with Jest

I've been trying to set up tests for some Angular components, but I keep running into an issue as all of my components use ng-lightning, which results in the following error:
/angular-lightning-test/node_modules/ng-lightning/ng-lightning.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ NgModule } from '#angular/core';
SyntaxError: Unexpected token import
I've tried multiple ways to get this going through Babel, though I'm not sure that should be required as Jest can handle it for every other file using import in this project.
I'm using jest-preset-angular to handle the setup for these tests. You can see the configuration it uses here.
I've created a very small sample project where you can see this error:
https://github.com/humantree/angular-lightning-test
The component is as simple as this:
#Component({
selector: 'badge',
template: '<ngl-badge>{{text}}</ngl-badge>'
}) export class BadgeComponent {
text = 'Test Badge';
}
and the test is as simple as this (I realize an actual test is missing, but the error still occurs before that would happen):
describe('BadgeComponent', () => {
let badge: BadgeComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BadgeComponent],
imports: [NglModule.forRoot()]
});
badge = TestBed.get(BadgeComponent).instance;
});
});
Can anyone see anything that I could add to my Jest configuration (or anything else) that would solve this error?
Note: For what it's worth, I also have these tests set up running in Mocha using mocha-webpack, and am having the exact same issue with that setup.
Thanks!
Try the following:
1) install the following packages: babel-jest, babel-preset-env
2) Add a .babelrc file at the your project root.
{ "presets": ["env"]}
3) Edit your jest.config.js file so babel process ng-lightning
{
"preset": "jest-preset-angular",
"transform": {
"^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!ng-lightning)"
]
}

Error in node_modules/react-native/Libraries/Modal/Modal.js while testing with Jest

I'm making a simple snapshot test with Jest and just get this error:
home.test.js
import React from 'react';
import Home from './index';
import renderer from 'react-test-renderer';
it('renders home', ()=> {
const view = renderer.create(
<Home></Home>
).toJSON();
expect(view).toMatchSnapshot();
});
Unfortunately I don't have idea what is the problem here. I thought the test is well written.
Any help would be great.
HOW I SOLVED THE ERROR KEEPING MY TEST FROM RUNNING
Ran into this error, which kept my tests from running
Error Page
After many hours of frustration, in which I deleted the node_modules folder twice and reinstalled and scoured through Stackoverflow and Google without any solution, I decided to create a new CRNA project and see if it would have the same issues.
When I saw the issues didn’t exist in the new repo, I used the following steps to get it to work:
Delete the node_modules folder again
Upgraded my package.json file, with the key changes shown below:
```
{
"devDependencies": {
"react-native-scripts": "1.5.0",
"jest-expo": "^21.0.2",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!react-native|expo|react-navigation|native-base-shoutem-theme|#shoutem/theme|#shoutem/animation|#shoutem/ui|tcomb-form-native)"
]
},
"dependencies": {
"react-native": “0.48.4”,
"expo": "^21.0.2",
"react": "16.0.0-alpha.12"
},
3. The core difference was in upgrading react-native from 0.48.0 to 0.48.4; react-native-scripts from 1.2.1 to 1.5.0 and including the transformIgnorePatterns under the jest option.
NOTE: The portion from *native-base* in the transformIgnorePatterns was included because I used NativeBase in the project.
4. I then added a .babelrc with the following details:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": ["transform-react-jsx-source"]
}
}
}
```
5. Running the tests now give me the result:
Passing Tests
All tests are green

How do I get JUnit XML output from Jest?

I have a React app that has Jest tests. I'm configuring Jest in my package.json:
…
"jest": {
"setupEnvScriptFile": "./test/jestenv.js",
"setupTestFrameworkScriptFile": "./test/setup-jasmine-env.js",
"testRunner": "node_modules/jest-cli/src/testRunners/jasmine/jasmine2.js",
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react"
]
},
…
The setup-jasmine-env.js looks like this:
var jasmineReporters = require('jasmine-reporters');
jasmine.VERBOSE = true;
jasmine.getEnv().addReporter(
new jasmineReporters.JUnitXmlReporter({
consolidateAll: true,
savePath: "output/",
filePrefix: "test-results"
})
);
It took a bit of working to get that jasmine env setup correctly, but I"m not seeing anything in the output directory (indeed, it isn't created and creating it myself doesn't help). I suspect that my alterations to the jasmine var aren't the same one that Jest is using, but I can't figure out how to hook them together.
If you use a more recent version of jest (I'm looking at 16.0.2), you don't need to specify the testrunner because jasmine is the default. You also don't need the unmockedModulePathPatterns section of the jest config.
I.e. you just need to include the following devDependencies in your package.json:
"jasmine-reporters": "^2.2.0",
"jest": "^16.0.2",
"jest-cli": "^16.0.2"
And add this jest config to your package.json (note: you no longer need the unmockedModulePathPatterns section):
"jest": {
"setupTestFrameworkScriptFile": "./setup-jasmine-env.js"
}
And then use Drew's setup-jasmine-env.js from the question.
Jest has support for its own reporters via the testResultsProcessor config. So I wrote up a little thing that generates compatible junit xml for this. You can find it here. https://github.com/palmerj3/jest-junit
looks like all you're missing from the above setup is to add jasmine-reporters to unmockedModulePathPatterns, so give the following a go:
"jest": {
...
"unmockedModulePathPatterns": [
"./node_modules/q",
"./node_modules/react",
"./node_modules/jasmine-reporters"
]
},
Hope that helps!
UPDATE: for anyone else experiencing this problem, I have put a working demo up here.

Categories