I'm trying to test a react component using both jest and enzyme, i've installed the necessary package for them, then configured my setupTests.js as shown below, but still have the same error that Enzyme module is not found, and "shallow" as well.
this is where i am trying to use Shallow from enzyme
import React from "react";
import { render, screen, cleanup } from '#testing-library/react'
import { shallow } from "#wojtekmaj/enzyme-adapter-react-17"
//some necessary local imports
// some other tests
describe('Welcome Component', () => {
it('renders Button component', () => {
const wrapper = shallow(<Welcome />);
expect(wrapper.containsMatchingElement(<NextButton text={"Next"}/>)).toEqual(true);
});
});
this is my setupTests.js
import '#testing-library/jest-dom';
import enzyme from 'enzyme';
import Adapter from '#wojtekmaj/enzyme-adapter-react-17';
enzyme.configure({ adapter: new Adapter() });
and here is my package.json
{
"name": "react-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.7.0",
"#emotion/styled": "^11.6.0",
"#fontsource/rubik": "^4.5.0",
"#material-ui/core": "^4.12.3",
"#mui/core": "^5.0.0-alpha.54",
"#mui/material": "^5.2.3",
"#reduxjs/toolkit": "^1.6.2",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/react": "^17.0.33",
"ajv": "^8.8.2",
"axios": "^0.24.0",
"bootstrap": "^5.1.3",
"enzyme": "^3.11.0",
"formik": "^2.2.9",
"fs": "0.0.1-security",
"icomoon-react": "^2.0.19",
"jest": "^27.4.5",
"jodit-react": "^1.1.11",
"js-file-download": "^0.4.12",
"lodash": "^4.17.21",
"lodash-redux-immutability": "0.0.3",
"popper.js": "^1.16.1",
"react": "^17.0.2",
"react-bootstrap": "^2.0.0",
"react-contenteditable": "^3.3.6",
"react-dom": "^17.0.2",
"react-icons": "^4.3.1",
"react-lottie": "^1.2.3",
"react-redux": "^7.2.6",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"react-split": "^2.0.13",
"react-split-pane": "^0.1.92",
"react-toast-notifications": "^2.5.1",
"react-web-vector-icons": "^1.0.2",
"redux-persist": "^6.0.0",
"redux-subscriber": "^1.1.0",
"reselect": "^4.1.5",
"web-vitals": "^1.0.1",
"xml2js": "^0.4.23",
"yup": "^0.32.11"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#wojtekmaj/enzyme-adapter-react-17": "^0.6.6",
"sass": "^1.43.2",
"sass-loader": "^12.2.0"
}
}
Install all these dependencies in dev. In my case I am using typescript, if
you are using javascript, skip types. Run npm i -D and all these
dependencies.
#types/enzyme
#types/enzyme-adapter-react-16
enzyme
enzyme-adapter-react-16
jest-environment-enzyme
jest-enzyme
#testing-library/jest-dom
#testing-library/react
#testing-library/user-event
#types/jest
ts-jest
In root of your project, create a file named jest.config.js and inside put this code :
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
modulePathIgnorePatterns: ["/dist/"],
};
In the same root of the project, create a file called jest.config.unit.js and put this code there:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
modulePathIgnorePatterns: ["<rootDir>/dist/"],
setupFilesAfterEnv: ["jest-enzyme"],
setupFiles: ['<rootDir>/src/setupEnzyme.ts'],
// ignore .js files
testRegex: '(/__tests__/.*|(\\.|/)(test))\\.[t]sx?$',
coverageReporters: ["lcov", "text"],
coverageDirectory: "test-coverage",
coverageThreshold: {
global: {
branches: 0,
functions: 0,
lines: 0,
statements: 0
}
}
};
Go to src folder, and create this file: setupEnzyme.ts(js), inside put this code:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
In src folder, create a file setupTests.ts(js) and put this code inside:
import '#testing-library/jest-dom';
Finally go to package.json, and under the scripts add this
"test": "jest -c jest.config.unit.js",
You are all set up. Create some test component, like Test.js which returns a simple div. Create a correspondent Test.test.js and add this test code:
import { shallow } from 'enzyme';
import { Test } from './test';
describe('<Test /> renders correctly', () => {
it('Renders correctly', () => {
const wrapper = shallow(<Test />);
expect(wrapper).toMatchSnapshot();
});
});
And if you run npm run test it should work.
Related
I have just runned create-react-app, moved some code and components from another project and now I cannot figure out why I get an error that it fails to compile. App component exist exactly in the destination where it can't be found. I suppose there is some hint in console, but I cannot figure out what can be the issue.
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./components/App/App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(
document.getElementById("root") as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Here I add a picture of App component to show You the location of app component.
Can You please suggest what is wrong here ?
Here You can see my package.json
{
"name": "flask_react",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"dependencies": {
"#emotion/react": "^11.10.5",
"#emotion/styled": "^11.10.5",
"#mui/material": "^5.11.5",
"#mui/x-date-pickers": "^5.0.15",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"#types/react": "^18.0.27",
"formik": "^2.2.9",
"prettier": "^2.8.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.7.0",
"react-scripts": "5.0.1",
"ts-loader": "^9.4.2",
"typescript": "^4.9.4",
"web-vitals": "^2.1.4",
"yup": "^0.32.11"
},
"scripts": {
"start": "react-scripts start",
"start-backend": "cd backend && env/bin/flask run --no-debugger",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"eslint": "eslint ./src/**/*.{ts,tsx}"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"#types/axios": "^0.14.0",
"#types/jest": "^27.5.2",
"#types/node": "^16.11.64",
"#types/react": "^18.0.21",
"#types/react-beautiful-dnd": "^13.1.2",
"#types/react-dom": "^18.0.6",
"#types/react-icons": "^3.0.0",
"#types/react-router": "^5.1.19",
"#types/react-router-dom": "^5.3.3",
"#typescript-eslint/eslint-plugin": "^5.39.0",
"#typescript-eslint/parser": "^5.39.0",
"env-cmd": "^10.1.0",
"eslint": "^8.24.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jsx-a11y": "^6.6.1",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.31.8",
"eslint-plugin-react-hooks": "^4.6.0",
"prettier": "^2.7.1",
"typescript": "^4.8.4"
}
}
import { App } from "./components/App/App";
You are destructuring your App import with the curly brackets, which returns undefined. Instead it should be
import App from './components/App/App';
EDIT: as Yuriy pointed out in the comments, since this isn't a default export then what I said above won't fix the problem. I have thought of something else though, what if you specify the extension? Like so
import { App } from "./components/App/App.tsx";
according to the error most probably here you are not including the .tsx extenstion to your extensions array. update your webpack.config.js file as below :
module.exports = {
// ...
resolve: {
extensions: [".js", ".jsx", ".ts", ".tsx"]
},
}
I'm learning to write a test for my react typescript app and come across this problem. I tried to use many different methods I found on internet but nothing work, the error is
Test suite failed to run
ReferenceError: expect is not defined
at Object.<anonymous> (node_modules/#testing-library/jest-dom/dist/extend-expect.js:7:1)
at Object.<anonymous> (node_modules/#testing-library/jest-dom/extend-expect.js:2:1)
This is my App.test.tsx file. Where error occur.
import React from 'react';
import App from './App';
import {render, fireEvent, waitFor, screen} from '#testing-library/react'
import "#testing-library/jest-dom/extend-expect";
import '#testing-library/jest-dom'
test('renders learn react link',async () => {
let screen = render(<App></App>);
expect(screen.getByText(/Hello/i)).toBeInTheDocument()
});
My package.json file
{
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#fontsource/roboto": "^4.5.1",
"#mui/material": "^5.2.7",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^7.1.2",
"#types/jest": "^27.4.0",
"#types/node": "^17.0.8",
"#types/react": "^17.0.38",
"#types/react-dom": "^17.0.11",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1",
"ts-jest": "^27.1.2",
"typescript": "^4.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"devDependencies": {
"#babel/preset-env": "^7.16.7",
"#babel/preset-react": "^7.16.7",
"babel-jest": "^27.4.6",
"jest": "^27.4.7",
"react-test-renderer": "^17.0.2"
}
}
And these are my jest.config.js and bebel.config.js file (Not sure if this matter)
module.exports = {
roots: ["<rootDir>/src"],
testMatch: [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)",
],
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
coveragePathIgnorePatterns: [
"/node_modules/"
],
moduleNameMapper: {
"\\.(css|less)$": "identity-obj-proxy",
},
"setupFiles": [
"<rootDir>/src/setupTests.ts"
]
};
module.exports = function (api) {
const presets = [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-flow'
];
const plugins = [
'#babel/plugin-transform-runtime',
];
api.cache(false);
return {
presets,
plugins
};
};
delete node_modules directory and do npm install
also replace the "setupFiles" with setupFilesAfterEnv in jest.config.js like following
setupFilesAfterEnv: [
'./setupTests.js',
],
try this in App.test.tsx
import React from 'react';
import App from './App';
import {render, fireEvent, waitFor, screen} from '#testing-library/react'
test('renders learn react link',async () => {
let screen = render(<App/>);
expect(screen.getByText(/Hello/i)).toBeInTheDocument()
});
I am using react-firebaseui for authentication, according to the documentation i have written the code
import React from "react";
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
import firebase from "firebase";
const firebaseConfig = {
...
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Configure FirebaseUI.
const uiConfig = {
// Popup signin flow rather than redirect flow.
signInFlow: "popup",
// Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
// signInSuccessUrl: '/signedIn',
// We will display Google and Facebook as auth providers.
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
};
export const SignInWith = () => (
<>
<p>Login</p>
<StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} />
</>
);
but i keep getting this error
./node_modules/firebaseui/dist/esm.js
Attempted import error: 'app' is not exported from 'firebase/app' (imported as 'firebase').`.
I tried importing firebase using import firebase from 'firebase/app, but still the same error.
I tried commenting StyledFirebaseAuth import and tag and it is working, so I am sure the problem is with react-firebaseui.
This is my package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^4.11.0",
"#material-ui/icons": "^4.9.1",
"#reduxjs/toolkit": "^1.4.0",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"#types/jest": "^24.9.1",
"#types/node": "^12.19.2",
"#types/react": "^16.9.54",
"#types/react-dom": "^16.9.9",
"#types/react-redux": "^7.1.9",
"axios": "^0.21.0",
"firebase": "^8.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-firebaseui": "^4.1.0",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.0",
"typescript": "^3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/react-router-dom": "^5.1.6",
"babel-plugin-import": "^1.13.1",
"customize-cra": "^1.0.0",
"react-app-rewired": "^2.1.6"
}
}
Thank you for any help.
Unfortunately, you've upgraded your "firebase" dependency to 8.0.0 but the "firebaseui" dependency doesn't support it yet. You will have to temporarily downgrade firebase to version 7.24.0 until firebaseui and react-firebaseui support the breaking changes in 8.0.0.
import firebase has changed with the version of 9.0.0, now there is compatibility available no need to downgrade, so you can use /compat folder in your imports,
import firebase from 'firebase/compat/app'
I created a React app with create-react last week.
I have a simple form that displays a message when I click submit.
I would like to test it, this is the test i created SampleForm.test.tsx:
import React from "react";
import { render, fireEvent, screen, waitFor } from "#testing-library/react";
import SampleForm from "./SampleForm";
import "#testing-library/jest-dom/extend-expect"
test("renders submits form", async () => {
const str = "THIS DIDNT DO ANYTHING";
const { container, getByText, findByText } = render(<SampleForm />);
fireEvent.click(screen.getByText("Submit"));
await waitFor(() => expect(screen.getByText(str)))
});
I'm getting an error at waitFor
TypeError: MutationObserver is not a constructor
stack trace:
at node_modules/#testing-library/dom/dist/wait-for.js:38:22
at waitFor (node_modules/#testing-library/dom/dist/wait-for.js:31:10)
at node_modules/#testing-library/dom/dist/wait-for.js:70:54
at node_modules/#testing-library/react/dist/pure.js:51:22
at node_modules/#testing-library/react/dist/act-compat.js:60:24
at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21856:12)
at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
at node_modules/#testing-library/react/dist/act-compat.js:59:20
at asyncAct (node_modules/#testing-library/react/dist/act-compat.js:38:14)
at Object.asyncWrapper (node_modules/#testing-library/react/dist/pure.js:50:35)
at waitForWrapper (node_modules/#testing-library/dom/dist/wait-for.js:70:35)
at Object.<anonymous> (src/components/SampleForm.test.tsx:18:11)
I have tried several different alterations of the style and text querying. Derived off of the samples here
This is the straight example i'm trying to get to work
I'm hesitant about adding shims and gyrations because according to the example I shouldn't have to do any of that. I'd like to understand why that example isn't working.
My package.json:
{
"name": "intact",
"version": "0.1.0",
"private": true,
"dependencies": {
"#rjsf/core": "^2.0.0-alpha.6",
"#testing-library/jest-dom": "^5.3.0",
"#testing-library/react": "^10.0.2",
"#testing-library/user-event": "^10.0.1",
"#types/jest": "^25.1.5",
"#types/lodash": "^4.14.149",
"#types/react": "^16.9.0",
"#types/react-dom": "^16.9.0",
"#types/react-router-dom": "^5.1.3",
"bootstrap": "^4.4.1",
"lodash": "^4.17.15",
"msal": "^1.2.2",
"react": "^16.13.1",
"react-aad-msal": "^2.3.4",
"react-bootstrap": "^1.0.0",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1",
"typescript": "^3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#types/fs-extra": "^8.1.0",
"#types/node": "^13.11.0",
"#types/rimraf": "^3.0.0",
"fs-extra": "^9.0.0",
"rimraf": "^3.0.2",
"ts-node": "^8.8.1"
}
}
edits: 04-05-2020
Are you running latest CRA? If so then this issue https://github.com/facebook/create-react-app/pull/8362 might be what you're experiencing. That's solvable by installing https://www.npmjs.com/package/jest-environment-jsdom-sixteen, e.g. $ yarn add -D jest-environment-jsdom-sixteen and editing your test script:
...
"scripts": {
...
- "test": "react-scripts test --env=dom"
+ "test": "react-scripts test --env=jest-environment-jsdom-sixteen"
...
},
...
"devDependencies": {
...
"jest-environment-jsdom-sixteen": "^1.0.3",
...
},
...
Essentially you will tell your jest to use jsdom v16 instead of v15(default for Jest v25).
I also faced the same issue.
Before trying the accepted answer, I updated react-scripts to version 4.0.1.
That solved the issue, because react-scripts 4.0.1 uses Jest 26.6.x.
Therefore, try upgrading react-scripts first.
I had this problem when I was running a very old version of node.js on Windows. When I updated to node version 12.16.3, the error disappeared.
This is my scene:
jest.config.js:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'enzyme',
setupFilesAfterEnv: ['jest-enzyme'],
setupFiles: ['./jest.setup.js'],
testEnvironmentOptions: {
enzymeAdapter: 'react16',
},
};
package.json:
"#testing-library/jest-dom": "^5.11.6",
"#testing-library/react": "^11.2.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"jest": "^26.6.3",
"jest-environment-enzyme": "^7.1.2",
"jest-enzyme": "^7.1.2",
"ts-jest": "^26.4.4",
"typescript": "^4.1.2"
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-router-dom": "^5.2.0",
Got error:
TypeError: MutationObserver is not a constructor
9 | const { getByTestId } = render(<Login />);
10 | expect(getByTestId('getUrl').getAttribute('href')).toEqual('');
> 11 | const url = await waitFor(() => getByTestId('getUrl'));
But when I changed the testEnvironment configuration:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
// testEnvironment: 'enzyme',
setupFilesAfterEnv: ['jest-enzyme'],
setupFiles: ['./jest.setup.js'],
testEnvironmentOptions: {
enzymeAdapter: 'react16',
},
};
The test passes:
PASS examples/65336283/LoginLink.test.tsx
65336283
✓ should display loginurl (23 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3 s, estimated 4 s
In my case, I was updating from an old version of jest and had to make sure to include the appropriate testing environment in package.json as none was set:
{
...
"scripts": {
...
"test": "jest --env=jsdom"
...
},
...
}
I want to use enzyme to perform unit tests in my React project with TypeScript.
I used documentation on adding tests to create-react-app - runnning tests
I created a setupTests.ts file in /src
setupTests.ts
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
And I wrote a test
App.test.ts
import React from 'react';
import { shallow } from 'enzyme';
import App from './App';
it('renders without crashing', () => {
shallow(<App />);
});
A test using react-dom works fine if I comment the line which configures adapter in setupTests.ts
setupTests.ts
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
// configure({ adapter: new Adapter() });
App.test.ts
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Dashboard';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
package.json
{
"name": "sampleapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.9.2",
"#material-ui/icons": "^3.0.2",
"#types/enzyme": "^3.9.1",
"#types/enzyme-adapter-react-16": "^1.0.5",
"#types/enzyme-to-json": "^1.5.3",
"#types/jest": "24.0.11",
"#types/node": "11.12.0",
"#types/react": "16.8.8",
"#types/react-dom": "16.8.3",
"#types/react-redux": "^7.0.5",
"#types/react-router-dom": "^4.3.1",
"#types/redux-thunk": "^2.1.0",
"axios": "^0.18.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-redux": "^6.0.1",
"react-router-dom": "^5.0.0",
"react-scripts": "2.1.8",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"typescript": "3.3.4000"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
The test is supposed to run successfully. But it is failing and giving me an error
Cannot find module 'enzyme' from 'setupTests.ts'
You should do yarn add enzyme and you'll be good!
Or npm i enzyme if you're using npm.
#types/enzyme is used to get typescript interfaces but not the actual enzyme package!