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!
Related
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'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.
I'm learning React at the moment, and I am currently trying out the Slate Markdown Editor in CodeSandbox. I am trying to initialize a Slate Editor instance like this:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Editor from "slate-md-editor";
const MdEditor = Editor();
<MdEditor />;
However, CodeSandbox displays the following error when I attempt to compile my code:
at evaluate (https://oxxbg.csb.app/node_modules/canner/slate-icon-codeblock/lib/index.js:80:45z
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:98419
X.evaluate
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110543
ye.evaluateTranspiledModule
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:120123
c
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110289
evaluate
https://oxxbg.csb.app/node_modules/slate-md-editor/lib/index.js:34:27
z
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:98419
X.evaluate
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110543
ye.evaluateTranspiledModule
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:120123
c
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110289
evaluate
/src/index.js:5
2 | import ReactDOM from "react-dom";
3 | import "./styles.css";
4 |
> 5 | import Editor from "slate-md-editor";
6 | const MdEditor = Editor();
7 |
8 | <MdEditor />;
I have not experienced this previously, and I am at a loss of knowing what to do.
I would greatly appreciate it if someone more experienced has some idea of this issue. Thank you in advance.
Link to the Sandbox
This is my package.json:
{
"name": "slate-editor",
"version": "1.0.0",
"description": "React testing project",
"keywords": [
"react",
"starter"
],
"main": "src/index.js",
"dependencies": {
"antd": "4.10.2",
"immutable": "4.0.0-rc.12",
"react": "17.0.0",
"react-dom": "17.0.0",
"react-scripts": "3.4.3",
"slate": "0.59.0",
"slate-md-editor": "1.5.4",
"slate-react": "0.59.0",
"slate-schema-violations": "0.1.39"
},
"devDependencies": {
"typescript": "3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Here is what I found out later:
Step 1
Setup a basic React project like so:
npx create-react-app slate-editor-demo
cd slate-editor-demo
Step 2
Delete the App.js, App.testing.js, and App.css in the src/ folder. You should now only have five files in that folder:
index.css
index.js
logo.svg
reportWebVitals.js
setupTests.js
Step 3
Install dependencies for slate-md-editor. Here they are:
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"antd": "^3.8.4",
"immutable": "^3.8.2",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-scripts": "1.1.5",
"slate": "^0.40.2",
"slate-react": "^0.12.0",
"slate-schema-violations": "^0.1.39",
"slate-md-editor": "1.5.4",
"web-vitals": "^1.0.1"
You can simply copy these dependencies into your package.json, and then run npm install to update the deps.
Step 4
Edit your src/index.js to look something like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Editor from "./slateMDEditor";
import reportWebVitals from './reportWebVitals';
const options = {
// default settings
prismOption: {
// https://github.com/GitbookIO/slate-prism
onlyIn: node => node.type === 'code_block',
getSyntax: node => node.data.get('syntax')
},
codeOption: {
// https://github.com/GitbookIO/slate-edit-code
onlyIn: node => node.type === 'code_block'
},
blockquoteOption: {
// https://github.com/GitbookIO/slate-edit-blockquote
},
listOption: {
// https://github.com/GitbookIO/slate-edit-list
types: ['ordered_list', 'unordered_list'],
typeItem: 'list_item',
typeDefault: 'paragraph'
}
}
const MdEditor = Editor(options);
ReactDOM.render(
<MdEditor onChange={this.onChange} />,
document.getElementById('root')
);
// Start measuring performance in app
reportWebVitals();
Step 5
Last step: run npm run start (if you use NPM), or yarn start (if you use yarn). You should see slate markdown editor running smoothly in your browser on localhost.
I am creating outlook add-in with react/typescript. When I run my code with npm run start, following message appeared and I was not able to run my react app.
Failed to compile.
./src/index.tsx
Line 9: 'Office' is not defined no-undef
Search for the keywords to learn more about each error.
In package.json, if react-script version is newer than 3.0.0, This error happens. If it is lower(e.x. 2.8.8), we can execute the react app without errors. Does anyone give me some workarounds?
Index.tsx
import 'react-app-polyfill/ie11';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { AppContainer } from './components';
import { Provider } from 'react-redux';
import { store } from './store/store';
Office.onReady(() => {
ReactDOM.render(
<Provider store={store}>
<AppContainer />
</Provider>,
document.getElementById('root')
);
});
package.json
"name": "outlookApp",
"version": "0.1.0",
"private": true,
"dependencies": {
"#microsoft/office-js": "^1.1.29",
"#microsoft/office-js-helpers": "^1.0.2",
"#types/jest": "24.0.11",
"#types/node": "11.13.6",
"#types/react": "16.8.23",
"#types/react-dom": "16.8.4",
"office-ui-fabric-react": "^6.190.1",
"react": "^16.8.6",
"react-app-polyfill": "^1.0.1",
"react-dom": "^16.8.6",
"react-redux": "^7.1.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.0",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"typescript": "3.4.4",
"uuid": "^3.3.2"
},
"devDependencies": {
"#types/gtag.js": "0.0.0",
"#types/office-js": "1.0.1",
"#types/react-redux": "^7.1.0",
"#types/react-router-dom": "^4.3.4",
"#types/uuid": "^3.4.5",
"redux-devtools-extension": "^2.13.8"
},
"scripts": {
"start": "react-scripts start",
"win": "set HTTPS=true&&set BROWSER=none&&react-scripts start",
"mac": "export HTTPS=true&&export BROWSER=none&&react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"test-win-ci": "set CI=true&&npm test",
"test-mac-ci": "CI=true npm test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"proxy": "http://localhost:7071"
}
One workaround is to just put the comment "/* global Excel, Office */" into the JS/TS/TSX file that it complains about, and things will magically work.
Note: The solution is taken from a comment at https://github.com/OfficeDev/office-js-docs-pr/issues/691. If anyone knowns of a better solution, please share it with the community!
I created a react app using create-react-app with typescript and trying to console log a couple of things from the test file but it's not working.
This is the tutorial I followed to set up create react app with typescript. I just added a console.log statement in the App.test.tsx file that comes with the setup and it didn't work.
It worked fine when I removed the 2 lines of code that used ReactDOM
package.json
{
"name": "testing2",
"version": "0.1.0",
"private": true,
"dependencies": {
"#types/jest": "24.0.11",
"#types/node": "11.12.0",
"#types/react": "16.8.10",
"#types/react-dom": "16.8.3",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "2.1.8",
"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"
]
}
App.test.tsx (doesn't work)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
console.log('hello thereeeeeeee');
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
App.test.tsx (works)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
console.log('hello thereeeeeeee');
const div = document.createElement('div');
// ReactDOM.render(<App />, div);
// ReactDOM.unmountComponentAtNode(div);
});
console.log statement is supposed to print. But it is not printing. The test is passing but the console statement is not printing when I use ReactDOM in the test