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"
}
}
Related
I am creating a shareable React component library.
The library contains many components but the end user may only need to use a few of them.
When you bundle code with Webpack (or Parcel or Rollup) it creates one single file with all the code.
For performance reasons I do not want to all that code to be downloaded by the browser unless it is actually used.
Am I right in thinking that I should not bundle the components? Should the bundling be left to the consumer of the components?
Do I leave anything else to the consumer of the components? Do I just transpile the JSX and that's it?
If the same repo contains lots of different components, what should be in main.js?
This is an extremely long answer because this question deserves an extremely long and detailed answer as the "best practice" way is more complicated than just a few-line response.
I've maintained our in-house libraries for 3.5+ years in that time I've settled on two ways I think libraries should be bundled the trade-offs depend on how big your library is and personally we compile both ways to please both subsets of consumers.
Method 1: Create an index.ts file with everything you want to be exposed exported and target rollup at this file as its input. Bundle your entire library into a single index.js file and index.css file; With external dependencies inherited from the consumer project to avoid duplication of library code.
(gist included at bottom of example config)
Pros: Easy to consume as project consumers can import everything from the root relative library path import { Foo, Bar } from "library"
Cons: This will never be tree shakable, and before people say to do this with ESM and it will be tree shakeable. NextJS doesn't support ESM at this current stage and neither do a lot of project setups that's why it's still a good idea to compile this build to just CJS. If someone imports 1 of your components they will get all the CSS and all the javascript for all your components.
Method 2: This is for advanced users: Create a new file for every export and use rollup-plugin-multi-input with the option "preserveModules: true" depending on how what CSS system you're using your also need to make sure that your CSS is NOT merged into a single file but that each CSS file requires(".css") statement is left inside the output file after rollup and that CSS file exists.
Pros: When users import { Foo } from "library/dist/foo" they will
only get the code for Foo, and the CSS for Foo, and nothing more.
Cons: This setup involves the consumer having to handle node_modules
require(".css") statements in their build configuration with NextJS
this is done with next-transpile-modules npm package.
Caveat: We use our own babel plugin you can find it here: https://www.npmjs.com/package/babel-plugin-qubic to allow people to import { Foo, Bar } from "library" and then with babel transform it to...
import { Foo } from "library/dist/export/foo"
import { Bar } from "library/dist/export/bar"
We have multiple rollup configurations where we actually use both methods; so for library consumers who don't care for tree shaking can just do "Foo from "library" and import the single CSS file, and for library consumers who do care for tree shaking and only using critical CSS they can just turn on our babel plugin.
Rollup guide for best practice:
whether you are using typescript or not ALWAYS build with "rollup-plugin-babel": "5.0.0-alpha.1"
Make sure your .babelrc looks like this.
{
"presets": [
["#babel/preset-env", {
"targets": {"chrome": "58", "ie": "11"},
"useBuiltIns": false
}],
"#babel/preset-react",
"#babel/preset-typescript"
],
"plugins": [
["#babel/plugin-transform-runtime", {
"absoluteRuntime": false,
"corejs": false,
"helpers": true,
"regenerator": true,
"useESModules": false,
"version": "^7.8.3"
}],
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-classes",
["#babel/plugin-proposal-optional-chaining", {
"loose": true
}]
]
}
And with the babel plugin in rollup looking like this...
babel({
babelHelpers: "runtime",
extensions,
include: ["src/**/*"],
exclude: "node_modules/**",
babelrc: true
}),
And your package.json looking ATLEAST like this:
"dependencies": {
"#babel/runtime": "^7.8.3",
"react": "^16.10.2",
"react-dom": "^16.10.2",
"regenerator-runtime": "^0.13.3"
},
"peerDependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0",
}
And finally your externals in rollup looking ATLEAST like this.
const makeExternalPredicate = externalArr => {
if (externalArr.length === 0) return () => false;
return id => new RegExp(`^(${externalArr.join('|')})($|/)`).test(id);
};
//... rest of rollup config above external.
external: makeExternalPredicate(Object.keys(pkg.peerDependencies || {}).concat(Object.keys(pkg.dependencies || {}))),
// rest of rollup config below external.
Why?
This will bundle your shit to automatically to inherit
react/react-dom and your other peer/external dependencies from the
consumer project meaning they won't be duplicated in your bundle.
This will bundle to ES5
This will automatically require("..") in all the babel helper functions for objectSpread, classes, etc FROM the consumer project which will wipe another 15-25KB from your bundle size and mean that the helper functions for objectSpread won't be duplicated in your library output + the consuming projects bundled output.
Async functions will still work
externals will match anything that starts with that peer-dependency suffix i.e babel-helpers will match external for babel-helpers/helpers/object-spread
Finally here is a gist for an example single index.js file output rollup config file.
https://gist.github.com/ShanonJackson/deb65ebf5b2094b3eac6141b9c25a0e3
Where the target src/export/index.ts looks like this...
export { Button } from "../components/Button/Button";
export * from "../components/Button/Button.styles";
export { Checkbox } from "../components/Checkbox/Checkbox";
export * from "../components/Checkbox/Checkbox.styles";
export { DatePicker } from "../components/DateTimePicker/DatePicker/DatePicker";
export { TimePicker } from "../components/DateTimePicker/TimePicker/TimePicker";
export { DayPicker } from "../components/DayPicker/DayPicker";
// etc etc etc
Let me know if you experience any problems with babel, rollup, or have any questions about bundling/libraries.
When you bundle code with Webpack (or Parcel or Rollup) it creates one single file with all the code.
For performance reasons I do not want to all that code to be downloaded by the browser unless it is actually used
It's possible to have separate files generated for each component. Webpack has such ability by defining multiple entries and outputs. Let's say you have the following structure of a project
- my-cool-react-components
- src // Folder contains all source code
- index.js
- componentA.js
- componentB.js
- ...
- lib // Folder is generated when build
- index.js // Contains components all together
- componentA.js
- componentB.js
- ...
Webpack file would look something like this
const path = require('path');
module.exports = {
entry: {
index: './src/index.js',
componentA: './src/componentA.js',
componentB: './src/componentB.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'lib'),
},
};
More info on "code splitting" is here in Webpack docs
If the same repo contains lots of different components, what should be in main.js?
There is a single field in package.json file named main, it's good to put its value lib/index.js according to the project structure above. And in index.js file have all components exported. In case consumer wants to use single component it's reachable by simply doing
const componentX = require('my-cool-react-components/lib/componentX');
Am I right in thinking that I should not bundle the components? Should the bundling be left to the consumer of the components? Do I leave anything else to the consumer of the components? Do I just transpile the JSX and that's it?
Well, it's up to you. I've found that some React libraries are published in original way, others - are in bundled way. If you need some build process, then define it and export bundled version.
Hope, all your questions are answered :)
You can split your components like lodash is doing for their methods.
What you probably have is separate components that you could allow importing separately or through the main component.
Then the consumer could import the whole package
import {MyComponent} from 'my-components';
or its individual parts
import MyComponent from 'my-components/my-component';
Consumers will create their own bundles based on the components they import. That should prevent your whole bundle being downloaded.
You should take a look at Bit, I think this is a good solution to share, reuse and visualize components.
It is very easy to setup. You can install your bit library or just a component with:
npm i #bit/bit.your-library.components.buttons
Then you can import the component in your app with:
import Button3 from '#bit/bit.your-library.components.buttons';
The good part is that you don't have to worry about configuring Webpack and all that jazz. Bit even supports the versioning of your components. This example shows a title-list react component so you can take a look if this meets your requirements or not
There is a configuration in webpack to create chunk files. To start with it will create the main bundle into multiple chunks and get it loaded as when required. if your project has well structured modules, it will not load any code which is not required.
I wanna use bit.dev as my react shared components store but I've stacked with compiling less files to css. I'm using create-react-app with customize-cra (to override CRA config without ejecting).
Here is my config-overrides.js file:
const { override, addLessLoader } = require('customize-cra');
module.exports = override(addLessLoader());
Here is my bit config from package.json:
"bit": {
"env": {
"compiler": "bit.envs/compilers/react#1.0.11"
},
"componentsDefaultDirectory": "components/{name}",
"packageManager": "yarn",
"defaultScope": "demkovych.spone-ui"
}
After bit build command finished, I still got .less file instead of .css.
Any suggestion how to use scss/less with bit.dev?
Right now the react compiler is only transpiling the code to plain javascript. The target application (consuming project) should compile the LESS files.
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 have a widget library that is created using React Native 0.55.3 and i am using the library in the web using React Native Web transpiler.
Currently my setup is React + TS + React Native Widgets (using RNW transpiler)
The library works fine in the web , but when i run the jest test case it starts complaining
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
I tried adding the following setup in the config file but with no avail .
"transformIgnorePatterns": [
"node_modules/(?!react-native-my-lib)"
],
Still it throws the same error , even tried adding transform and then pairing it to a mock file.
I am able to use the library in my project but the test case fails every-time
How can we fix this error ?
Right now what i have done in order to mitigate this issue is I have mocked the RN components as the RN components will be tested in their own Library and we will test the layout in React end mocking these components with string.
My solution [Please let me know if this is feasible]
create a mock file
module.exports = {
RN1COMP : '',
RN2COMP : ''
}
using module name mapper in jest
moduleNameMapper: {
"react-native-widgets": "<rootDir>/mocks/react-native-widgets.js"
},
Try this hope it works!!
"transformIgnorePatterns": [
"/node_modules/(?!(react-native|redux-persist|react-navigation.*?\\.js$))"]
Try this whole configuration in package.JSON
"jest" : {
"preset": "react-native",
"coveragePathIgnorePatterns": [
"allMocks.js"
],
"setupFiles": [
"<rootDir>/jest/allMocks.js"
],
"testPathIgnorePatterns": [
"/*/*.testdata.js$"
],
"transformIgnorePatterns": [
"/node_modules/(?!(react-native|redux-persist|react-navigation.*?\\.js$))"
],
"transform": {
"\\.(jpg|jpeg|PNG|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./fileTransformer.js"
},
"reporters": [
"default",
[
"./node_modules/jest-html-reporter",
{
"pageTitle": "Test Report",
"includeFailureMsg": true
}
]
]
}```
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)']