I'm implementing tests into an existing project that currently has no tests. My tests are failing to compile node_modules/ imports.
/Users/me/myproject/node_modules/lodash-es/lodash.js:10
export { default as add } from './add.js';
^^^^^^
SyntaxError: Unexpected token export
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
at Object.<anonymous> (app/reducers/kind_reducer.js:2:43)
at Object.<anonymous> (app/reducers/index.js:12:47)
The workaround I've found is to 'whitelist' node_modules in package.json jest config like this:
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
This seems like a hack because it takes over 1 minute to run a simple test that imports node_modules/lodash-es/lodash.js.
If none of the other solutions worked for you, you can try this in your jest
"moduleNameMapper": {
"^lodash-es$": "lodash"
}
It will replace lodash-es with the commonjs version during testing runtime.
I had to add this into my .jestconfig:
"transformIgnorePatterns": [
"<rootDir>/node_modules/(?!lodash-es)"
]
Posting a more complete answer here:
Jest by default does not transform node_modules because node_modules is huge. Most node modules are packaged to expose ES5 code because this is runnable without any further transformation (and largely backwards compatible).
In your case, lodash-es specifically exposes ES modules, which will need to be built by Jest via babel.
You can try narrowing your whitelist down so Jest doesn't try to pass every JavaScript file within node_modules through babel.
I think the correct configuration in your case is:
"jest": {
"transformIgnorePatterns": [
"/!node_modules\\/lodash-es/"
]
}
For create-react-app users who are looking for a fix, here's what worked for me:
// package.json
...
"jest": {
"transformIgnorePatterns": [
"<rootDir>/node_modules/(?!lodash-es)"
]
},
...
Overriding options in jest.config.js file didn't work for me. Keep in mind that not every option can be overridden, here's a list of supported options: https://create-react-app.dev/docs/running-tests#configuration
Probably someone finds this useful:
In my case, I have an Angular application that uses lodash-es package. During the testing, I am having the same error as the author.
OPatel's answer worked fine for me with a little tweak (add it to your jest.config.ts):
"moduleNameMapper": {
"lodash-es": "lodash"
}
After the changes I also needed to add the "esModuleInterop": true into my tsconfig.spec.json within the compilerOptions property to get rid of the TypeError: cloneDeep_1.default is not a function.
UPDATE:
After the solution above all the lodash methods return LodashWrapper instead of actual values e.g.
const clone = cloneDeep(object); // LodashWrapper
To get rid of this issue I used this solution:
https://github.com/nrwl/nx/issues/812#issuecomment-787141835
moduleNameMapper: {
"^lodash-es/(.*)$": "<rootDir>/node_modules/lodash/$1",
}
Renaming .babelrc to babel.config.js and adding transformIgnorePatterns worked for me.
module.exports = {
"presets": ["#babel/preset-env"]
}
P.S. My Jest version is:
"jest": "24.9.0"
babel-jest does not transpile import/export in node_modules when Babel 7 is used
I use pnpm, so I had to account for the symlink in the pattern, i.e.
transformIgnorePatterns: ['/node_modules/.pnpm/(?!lodash-es)']
Related
My React project works great. Some files need the raw-loader and I don't want to eject the project. So I have some raw-loader imports like this:
import blank_md from '!!raw-loader!./assets/blank.md.txt';
But jest dies with an error
Cannot find module '!!raw-loader!./assets/blank.md.txt' from ...
This is similar to Jest issue 4868
After adding jest-raw-loader I tried adding to Jest's config:
"transform": { "^!!raw-loader!.*": "jest-raw-loader" }
but no dice.
Using mocking would be fine too.
moduleNameMapper: {
"^!!raw-loader!.*": "jest-raw-loader",
}
This should load all the raw-loader import as required by jest.
Was looking for a solution myself and found that you should add the following module name mapping:
"moduleNameMapper": {
"^!!raw-loader!./assets/(.*)$": "<rootDir>/src/[insert path]/assets/$1"
}
Replacing with your correct path for the assets directory.
Edit: A nicer approach is just doing this tho
"moduleNameMapper": {
"^!!raw-loader!(.*)$": "$1"
}
I was able to use the Jest moduleNameMapper option to have Jest "use" the mock files.
The good news is that the Jest tests now run.
The bad news is that Jest still doesn't know how to load the files, so it supplies the filename to the app (instead of the file's contents). That's ok for my tests but is not optimal.
Here are some of the working settings that I'm using. I'm setting them in the package.json file:
"jest": {
"setupFiles": ["<rootDir>/src/tests/setup-register-context.js"],
"moduleNameMapper": {
"^!!raw-loader!.*sdkExamples.*txt": "<rootDir>/src/tests/__mocks__/templateMock.txt",
"^!!raw-loader!\\./toolbox.xml": "<rootDir>/src/tests/__mocks__/xmlMock.xml",
"^!!raw-loader!.*/assets/startBlocks.xml": "<rootDir>/src/tests/__mocks__/xmlMock.xml",
"!!raw-loader!.*md\\.txt": "<rootDir>/src/tests/__mocks__/mdMock.md"
}
}
I've just started using Cypress with my React Typescript project. I've gotten some simple tests to run:
describe('settings page', () => {
beforeEach(() => {
cy.visit('http://localhost:3000')
});
it('starts in a waiting state, with no settings.', () => {
cy.contains('Waiting for settings...')
});
it('shows settings once settings are received', () => {
const state = cy.window().its('store').invoke('getState')
console.log(state) // different question: how do I get this to be the state and not a $Chainer?
});
});
It runs in Cypress just fine. But I get Typescript errors in Webstorm, saying that cy is not defined (a TS and ESlint error) and an error on describe saying all files must be modules when the --isolatedModules flag is provided.
I can make it a JS file instead of a TS file, then I still get cy is not defined.
I've tried import cy from 'cypress' but then I get ParseError: 'import' and 'export' may appear only with 'sourceType: module' which is a whole other can of worms (I'm taking baby steps in writing my tests and haven't had to import anything yet...)
/// <reference types="cypress" /> does not work.
Update (sort of)
I've followed instructions here and have made a little progress. To my already very full React webpack.config.dev.js I added the recommended code:
{ // TODO inserted for cypress https://stackoverflow.com/a/56693706/6826164
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
to the end of the list of rules (just before the file loader).
When I do this as well as setting up the plugins/index file as indicated in the article, the cypress "home screen" runs but when I click to open my tests, it takes very many seconds and then shows lots of errors, starting with
integration\settings.spec.ts
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:
A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.
./cypress/integration/settings.spec.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\Users\...\...\front_end\cypress\integration\settings.spec.ts.
# multi ./cypress/integration/settings.spec.ts main[0]
Followed by, actually, a lot of Typescript output such as this:
C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(37,41)
TS2339: Property 'toBeTruthy' does not exist on type 'Assertion'.
C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(41,45)
TS2339: Property 'toBeDefined' does not exist on type 'Assertion'.
Notice that these are now errors for code outside the test files (although perhaps that makes sense). Many of them are for files in which I'm using Jest rather than Cypress, and many errors, as you can see, seem to be related to it inferring an Assertion type on expect that is not Jest, such that it thinks the toEqual matcher is wrong.
All the while, in Webstorm ESLint is still complaining about all my cy and TypeScript is underlining all those Jest assertions mentioned in the output.
This is all with a ts test file. If I rename the file to js, it says the file has no tests.
Any help? I love Cypress but I'm having a hell of a time getting it to work fully!
I got that error after upgrading to cypress version 4+. I installed the eslint-plugin-cypress
https://github.com/cypress-io/eslint-plugin-cypress
and activated it in the extends configuration either in package.json or in separate config file:
"eslintConfig": {
"extends": [
"plugin:cypress/recommended"
]
},
Add .eslintrc.json to cypress directory
In .eslintrc.json
{
"extends": [
"plugin:cypress/recommended"
]
}
I do not install eslint-plugin-cypress, and it fix the problem
Specify cy in eslintrc globals
Answered here
cy is a global variable. Much like location. So really it is window.cy. You can add it to the globals in Eslint. Don't import cy from cypress.
{
"globals": {
"cy": true
}
}
Added that to my .eslintrc and fixed the issue
The Cypress ESLint plugin will get rid of these warnings:
yarn add -D eslint-plugin-cypress (https://github.com/cypress-io/eslint-plugin-cypress)
add .eslintrc to the root of your project with the following:
{
"plugins": ["cypress"],
"extends": ["plugin:cypress/recommended"],
"rules": {
"jest/expect-expect": "off"
}
}
Try.. import cy from "cypress" this solved the problem for me.
at the top of your file put
/// <reference types="cypress" />
or download the official types
source: official cypress intellisense docs
I struggled a lot then this helped...
by adding same line in two files, eslintrc.json and eslintrc.js
(if u have other dependencies in extends, append them as well after it)
extends: ['plugin:cypress/recommended'],
Just add these lines to your tsconfig.json file for e2e tests:
"compilerOptions": {
"types": ["cypress"]
}
This adds support for cypress types.
/* global cy */
import above in your test file
example:
suppose you have login test ("cypress test file ex: cypress/integration/login.js")
I replaced the old style of type referencing,
/// <reference types="cypress" />
with this silly import
import type {} from 'cypress';
And the IDE now both recognizes Cypress's globals while also avoiding the "isolatedModules" issue it has with tsconfig.json
Seems I found a remedy that works (at least) for me. Adding this import to the top of the test:
import _Cypress from "cypress";
relaxes and comforts the ESLint plugin. Actually any name for the import can be used instead of "_Cypress": any that conforms your sense of beauty, does not conflict with anything and starts with underscore (to not provoke ESLint again). Of course, it looks like a kind of voodoo. I don't know why it works and probably there are better ways to present ESLint Cypress's globals, but I don't know them.
add this to jest.config.js
testPathIgnorePatterns: [
'/cypress',
],
Wrap your config object with defineConfig in the cypress.confi.ts file
like so
import { defineConfig } from "cypress";
export default defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
return config;
},
},
component: {
devServer: {
framework: "create-react-app",
bundler: "webpack",
},
},
});
For me adding .eslintignore in root directory and placing *.cy.js for all my test files was only workaround.
It seems that for the rest of us the working solution really is installing eslint-plugin-cypress and adding:
"eslintConfig": {
"extends": [
"plugin:cypress/recommended"
]
},
but idt didn't helped in my case because this plugin is no longer supported (almost for a year now) so it ended with critical error when combined with cypress-axe.
I trying to use crypto-js in react typescript run with docker compose , but I am getting the following error
Module not found: Can't resolve 'crypto-js' in '/app/crypto'
Here is that i imported crypto-js. For example:
import crypto from 'crypto-js';
export const encrypt = (key: string, evalue: any) => {
const secret_key = crypto.SHA256(key);
return crypto.AES.encrypt(evalue, secret_key).toString();
};
I have tried many times but it is not working.
My best guess is Typescript requires some type definitions for the packages.
Try to run npm install #types/crypto-js --save-dev
Regarding your tsconfig.json file, I believe it is because you are specifing "include": [ "src" ] so it means that all node_modules will be skipped.
Try removing it and using baseUrl option instead.
The types are not required for the project to build (unless you use the strict flag). But as #Kael said, it could be useful installing them. So you can specify
"typeRoots": [
"node_modules/#types"
],
in your config file
Try declaring in your types.d.ts
declare module 'crpyto-js' {
}
If that works, we now at least that your TypeScript settings should be correct.
Then you just have to install the #types/crypto-js package and delete your module declaration again.
If that doesn't work your typescript config doesn't your node_modules/#types folder.
Then set in your tsconfig.json your TypeRoots
"compilerOptions": {
"typeRoots" : ["./typings", "node_modules/#types"]
}
}
I'm currently using create-react-app to bootstrap one of my projects. Basically, I'm trying to set up paths in tsconfig.json by adding these to the default tsconfig.json generated by create-react-app:
"baseUrl": "./src",
"paths": {
"interfaces/*": [
"common/interfaces/*",
],
"components/*": [
"common/components/*",
],
},
However, every time I run yarn start which basically runs react-scripts start, it deletes my changes and generates the default configurations again.
How can I tell create-react-app to use my custom configs?
I was able to do this by using advice from this issue.
Put the configuration options react scripts likes to remove in a separate file (e.g. paths.json) and reference it from tsconfig.json via the extends directive.
paths.json:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"interfaces/*": [ "common/interfaces/*"],
"components/*": [ "common/components/*"],
}
}
}
tsconfig.json
{
"extends": "./paths.json"
...rest of tsconfig.json
}
Create React App does not currently support baseUrl. However there is a workaround...to setup baseUrl for both webpack and the IDE you have to do the following:
Create a .env file with the following code:
NODE_PATH=./
Create a tsconfig.paths.json file with the following code inside:
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"src/*": ["*"]
}
}
}
Add the following line to tsconfig.json
{
"extends": "./tsconfig.paths.json",
...
}
You can't and I am unsure when you will be able to. I have been trying to use baseUrl and paths so I can avoid relative imports but as you can see they are intentionally removing certain values. The "(yet)" is encouraging but (sigh) who knows when they will officially be supporting it. I recommend subscribing to this github issue to be alerted if/when this changes.
The following changes are being made to your tsconfig.json file:
- compilerOptions.baseUrl must not be set (absolute imports are not supported (yet))
- compilerOptions.paths must not be set (aliased imports are not supported)
If you are using react-scripts 4.0.0 like me then all you need to do is remove the line (around line 160 on my end):
paths: { value: undefined, reason: 'aliased imports are not supported' }
from the file node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
I was able to straight up add my baseUrl and paths config to my tsconfig.json file like so:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#domain/*": ["../src/domain/*"],
},
}
}
and finally compile and move on with my life.
Per usual, YMMV. Please test your stuff. This is obviously a hack but it worked for me so I'm posting here in case it helps someone.
Here's a patch if you feel like sharing with your team:
diff --git a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
index 00139ee..5ccf099 100644
--- a/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
+++ b/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
## -156,7 +156,8 ## function verifyTypeScriptSetup() {
: 'react',
reason: 'to support the new JSX transform in React 17',
},
- paths: { value: undefined, reason: 'aliased imports are not supported' },
+ // Removed this line so I can add paths to my tsconfig file
+ // paths: { value: undefined, reason: 'aliased imports are not supported' },
};
Edit
Per #Bartekus thoughtful suggestion in the comments thread I'm adding information on the package I use when I need to add (possibly) temporary changes like these to an npm package: patch-package
The package essentially provides a way to make changes to a package in a cleaner way. Especially when you consider collaboration it becomes very cumbersome to directly change an npm file and move on. The next time you update that package or even when you start developing in a new machine and run npm install your changes will be lost. Also, if you have teammates working on the same project they would never inherit the changes.
In essence you go through the following steps to patch a package:
# fix a bug in one of your dependencies
vim node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
# run patch-package to create a .patch file
npx patch-package react-scripts
# commit the patch file to share the fix with your team
git add patches/react-scripts+4.0.0.patch
git commit -m "Enable aliased imports in react-scripts"
Next time someone checks out the project and installs it, the patch will be applied automatically due to a post-install script you add during set up:
"scripts": {
+ "postinstall": "patch-package"
}
See up to date instructions in the package's documentation
I had a similar issue to this general problem (CRA overwrites "noEmit": false in my tsconfig.json of a React library I'm working on where I have two separate builds, one for local development, and another to build the production library with typings). Simple solution: use sed in a postbuild script in the package.json. For example: In-place edits with sed on OS X .
{
...
"scripts": {
...
"postbuild": "sed -i '' 's/{THING CRA IS REPLACING}/{WHAT YOU ACTUALLY WANT}/g' tsconfig.json # CRA is too opinionated on this one.",
...
}
...
}
This approach, however, is not cross-platform (unlike how rimraf is the cross-platform alternative to rm -rf).
For me, the problem was with VSCode using an older version of typescript (4.0.3), while the typescript version shipped with the project is (4.1.2).
The following did the trick for me:
Go to the command palette CTRL+Shift+P.
Choose "TypeScript: Select a TypeScript Version...".
Choose "Use workspace Version".
On Botpress (with react-scripts 4.0.3), we use a combination of 2 tricks to use paths without ejecting or patching the code. As Glenn and Microcipcip said, the first step is to extend the tsconfig.json file
tsconfig.path.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"~/*": ["src/*"],
"common/*": ["../bp/src/common/*"]
}
}
}
tsconfig.json
{
...
"extends": "./tsconfig.paths.json"
}
Then to make it work in the background, use the package react-app-rewired. It allows to make slight adjustments to the webpack configuration without actually ejecting CRA.
config-overrides.js
module.exports = {
webpack: (config, env) => {
config.resolve.alias['common'] = path.join(__dirname, '../bp/dist/common')
config.resolve.alias['~'] = path.join(__dirname, './src')
}
}
To see the full code, you can check the github repository https://github.com/botpress/botpress/tree/master/packages/ui-admin
For macOS this workaround should work.
package.json
"scripts": {
"start": "osascript -e 'tell app \"Terminal\" to do script \"cd $PATH_TO_REACT_APP && node ./setNoEmitFalse\"' && react-scripts start",
...
},
...
setNoEmitFalse.js
const fs = require('fs');
const { sleep } = require('sleep')
const path = './tsconfig.json'
const run = async () => {
sleep(2)
const tsconfig = fs.readFileSync(path, 'utf-8');
const fixed = tsconfig.replace('"noEmit": true', '"noEmit": false');
fs.writeFileSync(path, fixed)
}
run()
The execution of the javascript file in a separate terminal (osascript) provides the normal output for react-scripts in the original terminal.
Go to node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js and replace
const compilerOptions = {
...
};
by
const compilerOptions = { };
I generated a project with npx create-react-app my-app-ts --typescript,
then I created two files, sw-build.js and sw.js under src/,
the code of sw-build.js and sw.js is from (Guidlines for Using Workbox).
There is an error:
Cannot compile namespaces when the '--isolatedModules' flag is provided.
What should I do?
Just for others that may end up here, a potential answer was posted on the github issue listed above: Guidlines for Using Workbox.
karannagupta commented
I've excluded the SW files in tsconfig.json like this:
{
"compilerOptions": {
...
},
"include": [
"src/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts",
"src/sw-*.js",
"src/idb.js"
]
}
Edit:
Other options:
add // #ts-ignore to the line above the one with the error
add a nothing export (eg. export const _ = '';) so that the file is a module (from this ts issue)
A little hacky, but might be all someone needs...