expect is not defined in jest-dom - javascript

I get the following error on running npm test on my project, not created with create-react-app:
ReferenceError: expect is not defined
at Object.<anonymous> (/Users/ryedida/Desktop/threaded-messenger/node_modules/#testing-library/jest-dom/dist/extend-expect.js:7:1)
at Module._compile (internal/modules/cjs/loader.js:1256:30)
...
at require (internal/modules/cjs/helpers.js:75:18)
at Object.<anonymous> (/Users/ryedida/Desktop/threaded-messenger/src/componentTestUtils.js:1:1)
Setup
My root directory has a jest.config.js file, whose contents are
const config = {
verbose: true,
setupFilesAfterEnv: ['<rootDir>/src/componentTestUtils.js'],
testEnvironment: "jsdom"
};
module.exports = config;
componentTestUtils.js has
import '#testing-library/jest-dom/extend-expect';
import React from 'react';
import { MemoryRouter, Route } from 'react-router-dom';
import { render } from '#testing-library/react';
import App from '../components/App';
and defines some functions that I use. I am using Node 14.7, npm 7.6.3, #testing-library/jest-dom 5.12.0, #testing-library/react 11.2.6. My test script in package.json is
mocha --require #babel/register --reporter progress components/*.test.js
Similar Questions/Issues
My research in this issue has led me to
this GitHub issue in Enzyme, where a highly voted answer essentially says add the setupFilesAfterEnv key in the jest config
this GitHub issue in jest-dom, where the recommendations to upgrade #testing-library/jest-dom and #testing-library/react don't apply since my versions are higher, and their recommendation to upgrade from Node 10 to 12 also doesn't apply. Their other recommendation to add the same key above also did not work.
this GitHub issue in jest-native, the same setupFilesAfterEnv recommendation
this SO question with the same issue, but I already have the import in the accepted answer.
How do I solve this error?

Related

How to use import statement in one file without modifying package.json

I wish to use an import statement in a firebase.js file
to use the classic import of firebase :
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.11.0/firebase-app.js";
The limitations of the project dont allow me to install the firebase npm module
So I try to import it this way instead but I got the error
Cannot use import statement outside a module
So the only way I know is to add "type"="module" to my package.json file
but that'll just mess up the entire codebase relying on require, __dirname and other stuff which ecmascript does not support.
So Can I just convert one file type to a module
or is there any other way to import firebase from the url without installing the npm package
As a workaround, you can try to fork firebase sdk and install it adding to dependencies in package.json:
...
"dependencies" : {
....
"firebase": "url_to_your_fork.git",
....
}
And then do npm install.

Cannot find module 'immer' from 'node_modules/use-immer/dist/use-immer.js'?

I use useImmer in react project. Locally, everything starts, but in Github Actions and when deploying in Vercel, an error occurs with Immer. As I understand it, it does not find the required module.
import React, { useState } from 'react';
import { useImmer } from 'use-immer';
import getModal from './modals/index';
And the tests don't work because of the error.
GitHub Actions:
npm test -s
FAIL __tests__/test.jsx
● Test suite failed to run
Cannot find module 'immer' from 'node_modules/use-immer/dist/use-immer.js'
Require stack:
node_modules/use-immer/dist/use-immer.js
src/App.jsx
__tests__/test.jsx
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
at Object.<anonymous> (node_modules/use-immer/dist/use-immer.js:1:94)
And the deployment does not work.
Vercel:
15:11:16.184 ERROR in ./node_modules/use-immer/dist/use-immer.module.js 1:0-21
15:11:16.184 Module not found: Error: Can't resolve 'immer' in '/vercel/path0/node_modules/use-immer/dist'
Check whether immer is added as a dependency in your package.json. It's mentioned in peerDependencies of use-immer.

Solve having more than one copy of React in the same app

I'm developing a React module locally. For that, I'm linking my module using npm link.
The module is imported successfully but hooks are failing inside the module. It's throwing the following error:
Invalid hook call. Hooks can only be called inside of the body of a
function component. This could happen for one of the following
reasons: 1. You might have mismatching versions of React and the
renderer (such as React DOM) 2. You might be breaking the Rules of
Hooks 3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to
debug and fix this problem.
Checking the suggestions at React docs, I can confirm my app is using duplicate versions of React since the following code returns false:
// node_modules/mymodule/src/index.js
export { default as ReactFromModule } from 'react'
// src/index.js
import React from 'react'
import { ReactFromModule } from 'mymodule'
console.log(React === ReactFromModule) //false
This issue is full of suggestions but they are confusing. How can I solve it?
Note: Im not breaking rules of hooks, the error appears only when importing the module from an application.
In the module you are developing, add the conflicting packages to peerDependencies (and remove them from dependencies or devDependencies):
// package.json
"peerDependencies": {
"react": "16.13.1",
"react-dom": "16.13.1"
},
Execute npm install in your module.
Now add react and react-dom to the webpack configuration of your module as externals. These packages shouldnt be included in the bundle of the module (the app that uses the module will provide them):
// webpack.config.js
module.exports = {
/*
rest of config...
*/
output: {
filename: "index.js",
pathinfo: false,
libraryTarget: 'umd', // In my case, I use libraryTarget as 'umd'. Not sure if relevant
},
externals: {
// Use external version of React
"react": {
"commonjs": "react",
"commonjs2": "react",
"amd": "react",
"root": "React"
},
"react-dom": {
"commonjs": "react-dom",
"commonjs2": "react-dom",
"amd": "react-dom",
"root": "ReactDOM"
}
},
};
Then, after building your module, in your application you can check that both versions are now the same:
// node_modules/mymodule/src/index.js
export { default as ReactFromModule } from 'react'
// src/index.js
import React from 'react'
import { ReactFromModule } from 'mymodule'
console.log(React === ReactFromModule) // true :)
Adding react and react-dom as peerDependencies in the package.json didn't work for me.
I had to add an alias to the webpack configuration file:
// webpack.config.js
resolve: {
alias: {
react: path.resolve('./node_modules/react'),
}
In response to another comment, merely moving React to peerDependencies does not adequately resolve the issue in all cases. I would reply to that comment directly, but StackOverflow requires more reputation to respond to wrong answers than it does to post them.
I have a shared React component module built using Webpack and have run into the same issue. I've outlined one possible fix in this comment below which requires modifying peerDependencies and using npm link in a fashion similar to the answer shared by mtkopone.
https://github.com/facebook/react/issues/13991#issuecomment-841509933
My solution is a bit hacky and I wouldn't recommend it for long-term use. If you are using Webpack (which you tagged this question as), this article may detail a more permanent solution (https://medium.com/codex/duplicate-copy-of-react-errors-when-using-npm-link-e5011de0995d). I haven't tried it yet, but the author seems to have tried all the (incorrect) solutions out there and is also running into the hooks issue while trying to build shared component libraries.
The author of that article is trying to debug a Create-React-App app. While CRA uses webpack under the hood, you can't access the webpack.config directly, so the author has to perform some workarounds to do so. If you aren't using CRA, but just plain Webpack, then you could consider using the resolve.alias section of webpack.config to ensure there are no duplicate copies of React (see: https://blog.maximeheckel.com/posts/duplicate-dependencies-npm-link/)
I was attempting to use the peerDependencies and removal of the devDependencies and it was failing.
It turned out I had a node_modules folder in one of the parent folders of the library I was working on and the duplicate version of React was being loaded from there instead of the tool that was trying to use the React library.
Rather than editing the devDependencies to remove react I just wrote a small script to delete anything that's in the peerDependencies from the node_modules folder.
npm view --json=true . peerDependencies | jq -r 'keys | .[] | #text' | while read dep; do rm -r ./node_modules/${dep} && echo Removed ${dep}; done
In my case I was also missing import React from 'react' from couple of files.
check this

Apollo react import not transpiled when running jest tests

I'm currently experimenting an issue with my new React project using React and GraphQL Apollo. Here is my stack :
Webpack to build/dev to project
Babel to transpile javascript/jsx files
Jest to run tests
Enzyme to test my react components
The issue: When I run my tests, it seems that Apollo react client is not transpiled and throw tests :
pp/containers/App/__tests__/App.test.jsx
● Test suite failed to run
/Users/utilisateur/Project/TrAVis/TrAVis/node_modules/react-apollo/graphql.js:19
import { Component, createElement } from 'react';
^^^^^^
SyntaxError: Unexpected token import
1 | import React, { Component } from 'react';
> 2 | import graphql from 'react-apollo/graphql';
3 | import { bool, object, shape } from 'prop-types';
4 |
5 | import getUserQuery from './query';
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
at Object.<anonymous> (app/containers/App/App.jsx:2:16)
at Object.<anonymous> (app/containers/App/__tests__/App.test.jsx:4:12)
My jest configuration is :
module.exports = {
verbose: true,
moduleNameMapper: {
'\\.(css)$': 'identity-obj-proxy',
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
}
};
and my .babelrc is simply :
{
"presets": [
"react",
"es2015"
]
}
I found this issue https://github.com/facebook/jest/issues/3202 but it seems that the solution doesn't work with my project.
Can you help me?
Thank you,
SLedunois
You need to configure jest to handle es6 imports using babel-jest.
Add babel-jest to your project using the following command in your terminal.
npm install --save-dev jest babel-jest
In your jest.config.js file include the following under transform.
transform: {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
},
Also make sure you are importing react-apollo correctly.
Currect version 2.1.9 at time of writing imports using the following syntax.
import { graphql } from 'react-apollo';
By default Jest won't transform the contents of your node_modules folder, where your installation of Apollo resides.
There is a config option for Jest, called transformIgnorePatterns that provides the ability to change this behavior in order to transform some of your dependencies present in node_modules.
In your case, you need to whitelist Apollo so that Jest transforms it before running your tests:
"transformIgnorePatterns": ["node_modules\/(?!(react-apollo))"]
What happens here is that Jest will ignore all the contents of node_modules except react-apollo, which will get transformed with Babel. That way you should stop seeing the error you are getting.

Error in dist files Angular 2

Hi everyone at stackoverflow, I'm trying to release my Angular 2 app but I'm having issues with the dist files. First what I do is:
Clean the node_modules dir and remove the package-lock.json
Run the npm install and then npm update commands
After that I run the ng build --prod and everything is fine.
So, I check the dist folder and copy it to my server, and when I try to access it shows me an error:
Uncaught TypeError: Cannot read property 'create' of undefined
at vendor.7bb6292ce7eeab342f9a.bundle.js:1
at e.invoke (polyfills.0963b44a58b5526cfab7.bundle.js:1)
at Object.onInvoke (vendor.7bb6292ce7eeab342f9a.bundle.js:1)
at e.invoke (polyfills.0963b44a58b5526cfab7.bundle.js:1)
at r.run (polyfills.0963b44a58b5526cfab7.bundle.js:1)
at t.run (vendor.7bb6292ce7eeab342f9a.bundle.js:1)
at e._bootstrapModuleFactoryWithZone (vendor.7bb6292ce7eeab342f9a.bundle.js:1)
at e.bootstrapModuleFactory (vendor.7bb6292ce7eeab342f9a.bundle.js:1)
at Object.cDNt (main.e10f9a0cb71451c87757.bundle.js:1)
at n (inline.d31757e5f12d693ae92a.bundle.js:1)
I know is a library related issue because the minify is not working as intended, but I don't know which library is doing that since ng serve is working fine and showing no errors.
I don't know if there is some way to debug which library is doing this error or where it comes from.
This is what I get when I do the ng build --prod command. Also I included the enableProdMode();function already.
Update
Thanks everyone, the issue was that in my app.module.tsI had the platformBrowserDynamic().bootstrapModule(AppModule); and it was an error because in an updated version is in main.ts now and not in the app.module.ts so I had this duplicated and now everything is working fine. Thanks!
Have you seen the issue for this error here: https://github.com/angular/angular-cli/issues/5181 It suggests that it may be a problem with the platformBrowserDynamic setup in main.ts, especially if this app was started with an older/different version of Angular or the CLI.
My main.ts looks like this:
import { enableProdMode } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);

Categories

Resources