Jest React - Test suite failed to run, Cannot find module 'react-dotenv' - reactjs

I used Create React App to make a new project, and now i try to implement each feature i will need.
I am facing an issue i dont understand while trying to configure jest with reactjs.
One my node_modules, react-dotenv break jest test.
If i try to copy/past the issue line import env from 'react-dotenv'; directly in the root tested file Login.tsx there is no error.
I tried to configure moduleNameMapper and search around without success..
I dont understand the problem, what am i missing?

Ok, i was missing mocks and transformIgnorePatterns
Didn't really make transformIgnorePatterns working using:
transformIgnorePatterns: ["node_modules/(?!react-dotenv)"],
but the mocks
moduleNameMapper: {
'^.+\\.(css|scss)$': '<rootDir>/__mocks__/CSSStub.config.js',
'react-dotenv': '<rootDir>/__mocks__/react-dotenv.tsx'
},
did the job.

Related

Vitest with React Testing Library 'Unexpected Token'

I'm using react with ViteJS and Vitest for testing. I have set up the config for vitest and the test setup file too as you can see in the screenshots below.
vite.config.js
src/test/setup.ts
src/app/App.tsx
src/app/App.spec.js
here's the error I'm getting:
I found a lot of sources on similar issues about the topic but nothing I tried worked. I also followed the documentation for the vite config and a lot of articles too. Everyone is saying the same thing but I'm still getting this error for some reason.
I used the same config with jest and it worked fine. But in this situation, I got stuck and then tried to rename the filename to .tsx or .jsx instead of .ts or .js. After that, I re-ran the test file and everything started working.
I think you forgot to add #testing-library to vite.config.js alias object.
This might be obvious to most people but in my case the issue was that the test file also has to end in ".jsx" when trying to test a ".jsx" file.
App.test.jsx worked for App.jsx

How can i "externalize" material-ui from a react app

i am working on an react app creadted with the "create-react-app my-app --template cra-template-pwa-typescript" command.
Also i am using the material-ui package for the interface.
Now i want to use material-ui through an cdn. so i need to exclude this package via the "externals" config. I am using "react-app-rewired" to override the default config.
But i dont find a proper way to define the externals. found several examples,
for example:
externals = [
//...other externals working fine
/#material-ui\/.*/
]
or
externals = [
"#material-ui/core",
"#material-ui/icons",
/#material-ui\/core\/.*/,
/#material-ui\/icons\/.*/,
}
But when using this method i got an error while compiling
Failed to compile.
Failed to minify the code from this file:
external "#material-ui/core":1
Also tried the solution described here:
https://github.com/mui-org/material-ui/issues/11777#issuecomment-452306347
Here i dont get an error, but the material-ui package didnt excluded and is still bundled.

Using components from an external directory in a Electron project with Webpack

I am trying to do this as simple as possible, I studied Yarn Workspaces for a while, but that's a solution that's currently doesn't work with Electron, there were simply too many issues.
I have am Electron project here: ./electron/
I have a directory with components here: ./common/
The components are developed in React/JSX, there is nothing really fancy about them. That said, I am using hooks (useXXX).
I tried many ways to include those components (ideally, I wanted to use Yarn Workspaces, but it only multiplied the number of issues), but they all failed. Which is why I would like to avoid using yarn link or workspaces or making the common a library, etc. I just want my Electron project to behave as if the files were under ./electron. That's it.
The closest I came to a solution is by using electron-webpack, and overriding it with this config:
module.exports = function(config) {
config = merge.smart(config, {
module: {
rules: [
{
test: /\.jsx?$/,
//include: /node_modules/,
include: Path.resolve(__dirname, '../common'),
loaders: ['react-hot-loader/webpack', 'babel-loader?presets[]=#babel/preset-react']
},
]
},
resolve: {
alias: {
'#common': Path.resolve(__dirname, '../common')
}
}
})
return config
}
I can import modules, and they work... except if I use hooks. And I am getting the "Invalid Hook Call Warning": https://reactjs.org/warnings/invalid-hook-call-warning.html.
I feel like that /common folder is not being compiled properly by babel, but the reality is that I have no idea where to look or what to try. I guess there is a solution for this, through that webpack config.
Thanks in advance for your help :)
I found the solution. That happens because the instance of React is different between /common and /electron.
The idea is to add an alias, like this:
'react': Path.resolve('./node_modules/react')
Of course, the same can be done for other modules which need to be exactly on the same instance. Don't hesitate to comment this if this answer it not perfectly right.
I wrestled more than a day with a similar problem. My project has a dependency on a module A that is itself bundled by Webpack (one that I authored myself). I externalised React from A (declaring it to be a commonjs2 module). This will exclude the React files from the library bundle.
My main program, running in the Electron Renderer process, uses React as well. I had Webpack include React into the bundle (no special configuration).
However, this produced the 'hooks' problem because of two instances of React in the runtime environment.
This is caused by these facts:
module A 'requires' React and this is resolved by the module system of Electron. So Electron takes React from node_modules;
the main program relies on the Webpack runtime to 'load' React from the bundle itself.
both Electron and the Webpack runtime have their own module cache...
My solution was to externalise React from the main program as well. This way, both the main program and module A get their React from Electron - a single instance in memory.
I tried any number of aliases, but that does not solve the problem as an alias only gives direction to the question of where to find the module code. It does nothing with respect to the problem of multiple module caches!
If you run into this problem with a module that you cannot control, find out if and how React is externalised. If it is not externalised, I think you cannot solve this problem in the context of Electron. If it is externalised as a global, put React into your .html file and make your main program depend on that as well.

styles are `undefined` during test react application with jest

I'am creating a react application by using less instead of css, I added the less loader in the file config-overrides.js in order to use it with the package customize-cra. The application looks like perfect, nevertheless when I execute yarn test which launches jest runner all less styles are undefined so I cannot test if a component has a concrete className because it's undefined too. Should I add anything in the jest configuration in package.json in order to make less availale during testing ?
Thanks!

jest testing with es6 + jspm + systemjs + reactJS

I'm trying to figure out how to make my unit tests in my reactJS ES6 application. My application is already using es6 module system, transpiled with jspm/babel to systemJs.
I found babel-jest as preprocessor but even with it, I can't run my tests because jest can't find SystemJs. ("System is not defined" error is shown in the console)
In the browser, as explained in jspm documentation, SystemJs is loaded globally. I guess I should load SystemJs inside my preprocessor, but How can I make systemJs available for loading additional modules in my tests?
Thanks in advance
Unfortunately, Jest does not support SystemJS ES6 modules at the moment.
See the following comments:
So it sounds like jest assumes that your modules resolve based on the Node resolution algorithm.
Unfortunately this isn't compatible with SystemJS's resolution algorithm.
If there was a way in jest to set a "custom resolver" algorithm through an API then we could plug jspm into jest, but I'm not sure if this is currently possible.
-- Comment by Guy Bedford, creator of SystemJS, Jun 2015
It is unlikely there'll be official support for [SystemJS] unless it is a community contribution.
-- Comment by #cpojer, Jest Collaborator, Jan 2016
Also see the following issue: Invalid URL is thrown when requiring systemjs in jest test cases
in essence to get Jest to play nice with an app running on JSPM/SystemJS you need to "teach" it about all the mapping it holds in the config.js file (or however you call System.config())
the long answer is that you need to create an entry for each dependency you have installed with JSPM like this:
//jest configuration
moduleNameMapper: {
...
"^redux$": "redux#3.6.0",
...
}
for each alias you have, you need at least one entry:
moduleNameMapper: {
...
"^common\\/(.*)": "<rootDir>/src/common/$1", //for a dir alias
"^actions$": "<rootDir>/src/actions/index", //for a file alias
...
}
you also need to have these mappings in your nodeNameMapper:
moduleNameMapper: {
...
"^npm:(.*)": "<rootDir>/jspm_packages/npm/$1",
"^github:(.*)": "<rootDir>/jspm_packages/github/$1",
...
}
and finally, you need to have this moduleDirectories config:
moduleDirectories: ["node_modules", "jspm_packages/npm", "jspm_packages/github"]
this isnt really practical because you dont want to keep two copies of all your dependencies registry and have to sync them when they change...
so the short and better answer, you use my gulp-jest-jspm plugin :)
even if you dont use gulp, you can use its getJestConfig() method to generate the config for you before you run Jest.

Resources