wojtekmaj / enzyme-adapter-react-17 Goto Github PK
View Code? Open in Web Editor NEWUnofficial adapter for React 17 for Enzyme.
License: MIT License
Unofficial adapter for React 17 for Enzyme.
License: MIT License
Would it be possible to update to support react 18 without a whole rewrite?
I was attempting to run a test where we simulate a drag event on the page to make sure an upload region shows up. I get this error every time:
FAIL src/pages/__test__/TestPage.test.tsx (11.299 s)
TestPage
✕ drag event shows the upload region (52 ms)
● TestPage › drag event shows the upload region
TypeError: Cannot read property '__reactFiber$ul8w880oi5m' of null
9 |
10 | act(() => {
> 11 | wrapper.simulate('dragenter')
| ^
12 | })
13 |
14 | expect(wrapper.find(UploadRegion).exists())
at getInstanceFromNode (../../node_modules/react-dom/cjs/react-dom.development.js:10661:18)
at eventFn (../../node_modules/react-dom/cjs/react-dom-test-utils.development.js:2061:22)
at fn (../../node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:498:11)
at ../../node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:360:37
at batchedUpdates$1 (../../node_modules/react-dom/cjs/react-dom.development.js:22380:12)
at Object.act (../../node_modules/react-dom/cjs/react-dom-test-utils.development.js:1042:14)
at wrapAct (../../node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:360:13)
at Object.simulateEvent (../../node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:497:9)
at ReactWrapper.call (../../node_modules/enzyme/src/ReactWrapper.js:666:22)
at ReactWrapper.single (../../node_modules/enzyme/src/ReactWrapper.js:1170:21)
at ReactWrapper.simulate (../../node_modules/enzyme/src/ReactWrapper.js:665:17)
at src/pages/__test__/TestPage.test.tsx:11:15
at batchedUpdates$1 (../../node_modules/react-dom/cjs/react-dom.development.js:22380:12)
at act (../../node_modules/react-dom/cjs/react-dom-test-utils.development.js:1042:14)
at Object.<anonymous> (src/pages/__test__/TestPage.test.tsx:10:8)
at TestScheduler.scheduleTests (../../node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (../../node_modules/@jest/core/build/runJest.js:404:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 12.167 s
TestPage.test.tsx:
import { UploadRegion } from '@athena_docmgr/ui'
import { mount } from 'enzyme'
import { act } from 'react-dom/test-utils'
import { TestPage } from '../TestPage'
describe('TestPage', (): void => {
it('drag event shows the upload region', async () => {
const wrapper = mount(<TestPage />)
act(() => {
wrapper.simulate('dragenter')
})
expect(wrapper.find(UploadRegion).exists())
wrapper.unmount()
})
})
TestPage.tsx:
import { FunctionComponent } from 'react'
export const TestPage: FunctionComponent = () => {
return (
<>
<></>
<></>
<div>Some text</div>
</>
)
}
Of course that's not really what we're using, but the components for our page render that way, since we use a couple of components that either render empty fragments or nulls in certain cases.
It seems like this is a bug with nodeToHostNode
in ReactSeventeenAdapter
where the code assumes that if there is an array, we want the first element. See
However, in my case, the first two elements are null
, and the 3rd is the one we want. So, it seems like if we filter out null
values by using nodes.filter(Boolean)[0]
, my error is fixed and the problem goes away.
Can you update react peerDep to last 17 version plz?
I have such a setup file:
import * as Enzyme from 'enzyme';
import * as Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });
in package I have:
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.1"
"enzyme": "^3.11.0"
and my jest output is:
Test suite failed to run
TypeError: Adapter is not a constructor
2 | import * as Adapter from '@wojtekmaj/enzyme-adapter-react-17';
3 |
> 4 | Enzyme.configure({ adapter: new Adapter() });
| ^
at Object.<anonymous> (src/setupTests.js:4:29)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.466 s
Please help me to figure out this error
Hi,
thanks for your support. I got the following error:
FAIL src/tests/components/auth/mytest.test.js
● Test suite failed to run
TypeError: Cannot read property 'child' of undefined
4 | import Hello from "../../../components/auth/Hello";
5 |
> 6 | const wrapper = mount(<Hello/>);
| ^
7 |
8 | describe("Test", () => {
9 |
at getFiber (node_modules/@wojtekmaj/enzyme-adapter-react-17/src/detectFiberTags.js:15:31)
at detectFiberTags (node_modules/@wojtekmaj/enzyme-adapter-react-17/src/detectFiberTags.js:75:15)
at ReactSeventeenAdapter.createMountRenderer (node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:421:19)
at ReactSeventeenAdapter.createRenderer (node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:790:51)
at new ReactWrapper (node_modules/enzyme/src/ReactWrapper.js:113:32)
at mount (node_modules/enzyme/src/mount.js:10:10)
at Object.<anonymous> (src/tests/components/auth/mytest.test.js:6:17)
My test:
import "@testing-library/jest-dom";
import React from "react";
import { mount } from "enzyme";
import Hello from "../../../components/auth/Hello";
const wrapper = mount(<Hello/>);
describe("Test", () => {
test("<Hello></Hello> works", () => {
expect(wrapper).toMatchSnapshot();
});
});
My component:
import React from 'react'
export default function Hello() {
return (
<div>
<h1>Hello</h1>
</div>
)
}
Configuration:
import '@testing-library/jest-dom/extend-expect';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import {createSerializer} from 'enzyme-to-json';
Enzyme.configure({ adapter: new Adapter() });
expect.addSnapshotSerializer(createSerializer({mode: 'deep'}));
Package.json
{
"name": "journal-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"firebase": "^8.3.1",
"moment": "^2.29.1",
"node-sass": "^4.14.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.2",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"sweetalert2": "^10.15.6",
"validator": "^13.5.2"
},
"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": {
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.0",
"cloudinary": "^1.25.1",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.6.1",
"redux-mock-store": "^1.5.4"
}
}
I'm having an issue with testing Material-UI select option. Here I have tried to test all the options are loaded in the control. But when I put a console log debug it displays nothing on the options elements.
Also, I have noted that the menu items are rendered at the bottom of the page for Material-UI. Is there a specific way to get those? Below is the code that I have tried,
### Steps to Reproduce
ColorSelect.jsx
import React from 'react';
import { FormControl, MenuItem, Avatar, TextField } from '@material-ui/core';
import styled from "styled-components";
function ColorSelect(props) {
return (
<FormControl variant="outlined">
<TextField
id="color-id-input"
select
value={props.color}
label={props.color == "" ? "Color" : ""}
InputLabelProps={{ shrink: false }}
variant="outlined"
error={props.error}
helperText={props.helpertext}
>
<MenuItem style={{ fontSize: "13px" }} value="">
<em>None</em>
</MenuItem>
{
props.colors.map(color => (
<MenuItem key={"ColorNewLineMenuItem_" + color.colorCode} style={{ fontSize: "13px" }} value={color.colorCode}>
<div>
<Avatar key={"ColorNewLineAvatar_" + color.colorCode} src={color.imageSrc} />
<div>{color.name}</div>
</div>
</MenuItem>
))
}
</TextField>
</FormControl>
)
}
export default ColorSelect;
ColorSelect.test.js
import * as React from 'react';
import MockProvider from '../../mockProvider';
import * as data from '../../data/poData.json';
import { act } from '@testing-library/react';
import { mount } from "enzyme";
import ColorSelect from '../../../components/order/ColorSelect';
test("check colors dropdown loads correctly", async () => {
wrapper = mount(<MockProvider><ColorSelect color="" colors={data.products[0].colors} />
</MockProvider>);
await act(async () => {
wrapper.find({ 'id': "color-id-input" }).last().simulate("click")
});
wrapper.update();
console.log(wrapper.debug()) // Can't see the menu items
}
This is what the log shows,
Hi guys.
Could someone add support for React 17.0.2?
The node names changed after upgrading from react 16 with official enzyme-adapter-react-16.
Dependencies:
"react": "^17.0.1",
"@wojtekmaj/enzyme-adapter-react-17": "^0.4.1",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.6.1",
The following test can reproduce the problem (using jest):
test.only('Nested component snapshot', () => {
// Arrange
const DummyComponent = (_, ref) => <div ref={ref} />;
const MemoForwardComponent = React.memo(React.forwardRef<HTMLDivElement>(DummyComponent));
const Component: React.FC = () => <MemoForwardComponent />;
// Act
const wrapper = shallow(<Component />);
// Assert
expect(wrapper).toMatchInlineSnapshot(`<Memo(ForwardRef(DummyComponent)) />`);
});
This React 16 is succeeding, but with React 17 with @wojtekmaj/enzyme-adapter-react-17 v0.4.1 is failing with the following message:
● Nested component snapshot
expect(received).toMatchInlineSnapshot(snapshot)
Snapshot name: `Nested component snapshot 1`
- Snapshot - 1
+ Received + 1
- <Memo(ForwardRef(DummyComponent)) />
+ <Memo([object Object]) />
19 |
20 | // Assert
> 21 | expect(wrapper).toMatchInlineSnapshot(`<Memo(ForwardRef(DummyComponent)) />`);
| ^
22 | });
23 |
24 |
Seems the
This is related to the following issue in the official enzyme react 16 adapter: enzymejs/enzyme#2481
Hi, I've switched over to this library as part of our React 17 upgrade. We are using React Native.
I've noticed that all our snapshots (several thousand) in the project failed due to the displayName
of many components changing to a generic Component
.
I think this is to do with the Object.assign
forcing the display name to be Component
in the methods wrapPureComponent
and wrapFunctionalComponent
.
Is this right and can anything be done about it?
p.s. I think it's great that you have released this despite the Enzyme maintainers refusing to release their React 17 adapter!
Do we need to import React in test file, because it is not required in components with React V17 and above . As I am getting errors ReferenceError: React is not defined in my tests file
The error I'm seeing:
console.error
Warning: Failed prop type: Invalid prop `nodeRef.current` of type `HTMLDivElement` supplied to `Transition`, expected instance of `Element`.
at Transition (...\node_modules\react-transition-group\cjs\Transition.js:133:30)
at Fade (...\node_modules\@material-ui\core\node\Fade\Fade.js:53:5)
at Backdrop (...\node_modules\@material-ui\core\node\Backdrop\Backdrop.js:70:44)
at MuiDialog-backdrop (...\node_modules\@emotion\react\dist\emotion-element-cb6e9ca7.cjs.dev.js:35:23)
at div
at MuiModal-root (...\node_modules\@emotion\react\dist\emotion-element-cb6e9ca7.cjs.dev.js:35:23)
at Portal (...\node_modules\@material-ui\unstyled\node\Portal\Portal.js:31:5)
at ModalUnstyled (...\node_modules\@material-ui\unstyled\node\ModalUnstyled\ModalUnstyled.js:77:5)
at Modal (...\node_modules\@material-ui\core\node\Modal\Modal.js:81:44)
at MuiDialog-root (...\node_modules\@emotion\react\dist\emotion-element-cb6e9ca7.cjs.dev.js:35:23)
at Dialog (...\node_modules\@material-ui\core\node\Dialog\Dialog.js:206:44)
at div
at StandardSelector ([my_workding_dir_path]\src\intercept\standardselector.tsx:25:5)
at WrapperComponent (...\node_modules\@wojtekmaj\enzyme-adapter-utils\src\createMountWrapper.jsx:48:26)
This same warning happens for multiple components under test.
The triggering Components seem to follow the same structure.
import React, { ReactElement } from "react"
import {
Button,
Dialog,
DialogActions,
DialogContent,
TextField,
} from "@material-ui/core"
type MyProps = {
someProp: string
}
type MyState = {
showDialog: boolean
}
export default class MyComponent extends React.PureComponent<MyProps, MyState> {
constructor(props: IRProps) {
super(props)
this.state = {
showDialog: false,
}
}
/**
* Toggle the dialog display when the control button is pressed,
* or hide when clickaway happens
*/
handleToggleDialog = (): void => {
this.setState((prevState) => ({ showDialog: !prevState.showDialog }))
}
handleSubmit = ():void=>{
// ...
}
/**
* Handle dialog cancel button click
*/
handleCancelClick = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
): void => {
event.preventDefault()
this.setState({ showDialog: false })
}
render(): ReactElement {
const { showIssueForm } = this.state
return (
<div style={{ width: "25%" }}>
<button
type="button"
style={{ marginLeft: "5%", top: "5px" }}
onClick={this.handleToggleDialog }
>
Open Dialog
</button>
<Dialog
fullScreen={false}
open={showDialog}
onClose={this.handleToggleDialog }
>
<DialogContent>
Some text with a <a href="google.com">link</a>
</DialogContent>
<DialogActions>
<Button
id="submitButton"
onClick={this.handleSubmit}
disabled={!submitEnabled}
>
Submit
</Button>
<Button id="cancelIssueReport" onClick={this.handleCancelClick}>
Cancel
</Button>
</DialogActions>
</form>
</Dialog>
</div>
)
}
}
Ultimately, this is just an inconvenience in that "npm run coverage" will spam errors; for now I've been hiding with a beforeAll in each of the affected unit tests to silence it.
beforeAll(() => {
console.warn(
"05/07/2021- Surpressing external usage of console.error\r\n" +
"Use '(test command) --silent' to turn off all console messages."
)
jest.spyOn(console, "error").mockImplementation()
})
Just wondering if this is a problem internally to one of the external modules, or if I need to restructure my components so they conform to the expected types.
Whenever I mount a tree with React.Suspense, it throws:
Error: Enzyme Internal Error: unknown node with tag 23
at _toTree (/Users/jetbrains/IdeaProjects/TeamCity/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:166:3)
at childrenToTree (/Users/jetbrains/IdeaProjects/TeamCity/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:292:4)
Brief debugging showed that this probably is the new Offscreen
fiber type
I have tried using this enzyme adapter in our codebase with React 17 and all tests passes fine except the ones using renderProp
.
The following test (simple version of this example https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/renderProp.html) works fine with React 16 and enzyme-adapter-react-16 but not when using ver 17
const App = () => <Component render={() => <div>render</div>} />;
const Component = () => <div />;
it('should render prop', () => {
const wrapper = shallow(<App />)
.find(Component)
.renderProp('render')();
expect(wrapper.equals(<div>render</div>)).toEqual(true);
});
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react-native": "10.1.1",
"@testing-library/user-event": "^14.4.3",
@wojtekmaj/enzyme-adapter-react-17
"expo": "^44.0.0",
"jest": "29.0.2",
"jest-expo": "^46.0.1",
"jest-environment-jsdom": "^28.1.2",
"jest-expo-enzyme": "^1.4.0",
"jsdom": "^20.0.0",
"jsdom-global": "^3.0.2",
"react-test-renderer": "17.0.1",
While using React 17
, MUI 5, and latest version of @wojtekmaj/enzyme-adapter-react-17
(which is 0.6.7), when we try to simulate an event (like click
or mouseenter
) on MUI components like Button
, IconButton
or Tab
, we get an error like TypeError: Cannot read property '__reactFiber$g9li6s00347' of undefined
Here is a CodeSandbox reproducing the error - https://codesandbox.io/s/react17-enzyme-simulate-click-49y6pb?file=/src/components/BasicButton.test.js
I also created a CodeSandbox to see if there is such an error while using enzyme-adapter-react-16
with React 16
and MUI 4
. But I didn't find such an error in it. Here is that CodeSandbox - https://codesandbox.io/s/react16-enzyme-simulate-click-67w2pj?file=/src/components/BasicButton.test.js
I think this issue is similar to the issue - #42. In that issue, return value of _nodeToHostNode
in ReactSeventeenAdapter
was some null values followed by non-null value. In this case though, all values returned from _nodeToHostNode
are null
.
Hi, I tried to test on a component with multiple children wrapped in <Suspense />
, like:
<Suspense fallback={...}>
<div />
<div />
<div />
</Suspense>
Only the first div
rendered in test framework.
Here's the reproduction link. It looks good on browser and React Testing Framework but failed on Enzyme. Is it a bug of React 17 adapter?
React 17, using all the latest packages.
"@emotion/css": "^11.5.0",
"@emotion/react": "^11.6.0",
"@emotion/styled": "^11.6.0",
"@types/enzyme": "^3.10.10",
"@types/enzyme-adapter-react-16": "^1.0.6",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.5",
"@mui/material": "^5.2.2",
"@mui/styles": "^5.2.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"enzyme-to-json": "^3.6.2",
I follow one of the enzyme unit test workaround to include Mui's ThemeProvider + styled-components's ThemeProvider
function UnitTestThemeWrapper (props: any) {
// console.log(props.theme);
return (
<StyledEngineProvider injectFirst>
<MuiThemeProvider theme={props.theme || LightTheme}>
<ThemeProvider theme={props.theme || LightTheme}>
<GlobalStyle />
<CssBaseline />
{props.children}
</ThemeProvider>
</MuiThemeProvider>
</StyledEngineProvider>
);
}
const shallowWithTheme = (node: ReactElement, options?: ShallowRendererProps): ShallowWrapper => {
// The only way to get it to work, is to manually wraps the node ourselves.
// return shallow(UnitTestThemeWrapper(node), options);
// Note: For some reason the wrappingComponent from Enzyme is broken.
// It would not properly calls the wrappingComponent when using shallow.
// It throws a cryptic error message which has nothing to do with the issues:
// "Method “type” is meant to be run on 1 node. 3 found instead."
options = options || {
wrappingComponent: UnitTestThemeWrapper
};
return shallow(node, options); // <= this throw "Method type is meant to be run on 1 node. 3 found instead.
// */
};
My UT only has the following:
describe('Blah', () => {
let wrapper: ShallowWrapper | ReactWrapper;
it('should render', () => {
wrapper = shallow(<Menu open={false} anchorEl={dummy} />);
});
});
How can I get this to work?
Hi,
I know that this adapter is temporary and the only way to use enzyme with React 17 and I am not sure how much time do you invest in its maintenance, but if you do, I met error which I was trying to solve in past year without success. I ran into it again after few months so I decided to create this issue.
I have been updating our open-source React UI library (still in development) and as part of maintenance task I have been trying to update React 16 to React 17 and use your adapter for React 17. But if I do this, some tests fail with error:
Cannot read property 'child' of undefined
TypeError: Cannot read property 'child' of undefined
at getFiber (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/detectFiberTags.js:15:31)
at detectFiberTags (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/detectFiberTags.js:75:15)
at ReactSeventeenAdapter.createMountRenderer (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:421:19)
at ReactSeventeenAdapter.createRenderer (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/ReactSeventeenAdapter.js:792:51)
at new ReactWrapper (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/enzyme/src/ReactWrapper.js:113:32)
at mount (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/enzyme/src/mount.js:10:10)
at Object.<anonymous> (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/src/lib/components/ui/Alert/__tests__/Alert.test.jsx:10:18)
at Promise.then.completed (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/utils.js:390:28)
at new Promise (<anonymous>)
at callAsyncCircusFn (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/utils.js:315:10)
at _callCircusTest (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/run.js:218:40)
at _runTest (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/run.js:155:3)
at _runTestsForDescribeBlock (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/run.js:66:9)
at _runTestsForDescribeBlock (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/run.js:60:9)
at run (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/run.js:25:3)
at runAndTransformResultsToJestFormat (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js:166:21)
at jestAdapter (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js:82:19)
at runTestInternal (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-runner/build/runTest.js:389:16)
at runTest (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-runner/build/runTest.js:481:34)
at TestRunner.runTests (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest-runner/build/index.js:111:12)
at TestScheduler.scheduleTests (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@jest/core/build/runJest.js:387:19)
at _run10000 (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@jest/core/build/cli/index.js:408:7)
at runCLI (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/@jest/core/build/cli/index.js:261:3)
at Object.run (/Users/bedrich.schindler/VisionApps/Projekty/va/react-ui/node_modules/jest/node_modules/jest-cli/build/cli/index.js:163:37)
Weird thing is that only some of tests fail with this error.
Enzyme configuration tests/setupEnzyme.js (different from git version as I have those changes on local machine only):
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { createSerializer } from 'enzyme-to-json';
// Configure enzyme to use adapter for React
Enzyme.configure({ adapter: new Adapter() });
// Configure jest to use json serializer for snapshot creation
expect.addSnapshotSerializer(createSerializer({
ignoreDefaultProps: true,
mode: 'deep',
noKey: true,
}));
Example test src/lib/components/ui/Alert/tests/Alert.test.jsx:
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import defaultTranslations from '../../../../translations/en';
import { Alert } from '../Alert';
describe('rendering', () => {
it('renders correctly', () => {
const tree = mount(
<Alert translations={defaultTranslations.Alert}>
<div>Children</div>
</Alert>,
);
expect(shallowToJson(tree)).toMatchSnapshot();
});
it('renders correctly with all props', () => {
const tree = mount(
<Alert
closeHandler={() => {}}
color="success"
icon={<span className="icon" />}
id="custom-id"
translations={defaultTranslations.Alert}
>
<div>Children</div>
</Alert>,
);
expect(shallowToJson(tree)).toMatchSnapshot();
});
});
Example test src/lib/components/ui/Alert/Alert.jsx:
import PropTypes from 'prop-types';
import React from 'react';
import getRootColorClassName from '../../../helpers/getRootColorClassName';
import { withProviderContext } from '../../../provider';
import styles from './Alert.scss';
export const Alert = ({
children,
closeHandler,
color,
icon,
id,
translations,
}) => (
<div
className={[
styles.root,
getRootColorClassName(color, styles),
].join(' ')}
id={id}
role="alert"
>
{icon && (
<div className={styles.icon}>
{icon}
</div>
)}
<div
className={styles.message}
{...(id && { id: `${id}__content` })}
>
{children}
</div>
{closeHandler && (
<button
type="button"
{...(id && { id: `${id}__close` })}
className={styles.close}
onClick={() => closeHandler()}
onKeyPress={() => closeHandler()}
tabIndex="0"
title={translations.close}
>
<span className={styles.closeSign}>×</span>
</button>
)}
</div>
);
As we use named export of Alert component instead of default export with React Context, there should not be any problem as there is almost anything to fail. But even if i replace content of the component with <div />
, it fails with same error. But it happens only for tests using mount
, shallow
tests works fine.
Hi,
I tried to use the adapter in a Typescript environment.
My .mocharc.json
require ts-node
and my adapter setup file:
{
"recursive": true,
"require": [
"ts-node/register",
"./spec/support.ts"
]
}
My support.ts
file is:
// ./spec/support.ts
import * as Enzyme from "enzyme";
import Adapter from "@wojtekmaj/enzyme-adapter-react-17";
console.log("Adapter =", Adapter); // Adapter = undefined
Enzyme.configure({ adapter: new Adapter() });
The imported Adapter is undefined
. It works fine though in Javascript.
{
"recursive": true,
"require": [
"ts-node/register",
"./spec/support.js"
]
}
// ./spec/support.js
const Enzyme = require("enzyme");
const Adapter = require("@wojtekmaj/enzyme-adapter-react-17");
Enzyme.configure({ adapter: new Adapter() });
I get an error
Cannot find module 'react' from '../node_modules/@wojtekmaj/enzyme-adapter-react-17/build/ReactSeventeenAdapter.js'
I installed react both in dependencies and devdependencies
Here's my test file:
import React, { useEffect, useState } from "react";
import Enzyme from 'enzyme';
import EnzymeAdapter from '@wojtekmaj/enzyme-adapter-react-17';
import App from './App'
Enzyme.configure({ adapter: new EnzymeAdapter() });
test ('renders learnt react link', ()=> {
const {getByText} = render(<App />);
const title = getByText("Search and Select Snippets");
expect (title).toBeInTheDocument();
})
Here's my package.json:
{
"name": "axwayprerequisites",
"homepage": ".",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"axios": "^0.21.0",
"bootstrap": "^4.5.3",
"dompurify": "^2.2.0",
"env-cmd": "^10.1.0",
"jquery": "^3.5.1",
"logrocket": "^1.0.14",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-hook-form": "^6.9.6",
"react-scripts": "4.0.0",
"react-select": "^3.1.0",
"react-tabs": "^3.1.1",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"start:local": "env-cmd -f ./.env.local react-scripts start",
"start:testlocal": "env-cmd -f ./.env.testlocal react-scripts start",
"start:test_remoteserver_localclient": "env-cmd -f ./.env.test_remoteserver_localclient react-scripts start",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build": "env-cmd -f ./.env.local react-scripts build",
"build:local": "env-cmd -f ./.env.local react-scripts build",
"build:prod": "env-cmd -f ./.env.prod react-scripts build",
"build:remoteTestServer": "env-cmd -f ./.env.remoteTestServer react-scripts build",
"toto": "env-cmd -f ./.env.toto node toto.js"
},
"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": {
"enzyme": "^3.11.0",
"react": "^17.0.1"
}
}
Hello, I've tried to bump @wojtekmaj/enzyme-adapter-react-17
to 0.6.3
and doing so results in yarn complaining about "Workspaces can only be enabled in private projects".
I'm guessing it's caused by this project root package.json
being used by the NPM module as opposed to the module living in a workspace and the root being a private module and managing all workspaces in the repository. There's a report about it here in yarn repository.
Hi,
Thanks for sharing this adapter. I get the following error:
The following test generates an error TypeError: Cannot read property 'configure' of undefined
import { shallow, Enzyme } from 'enzyme'
import Groot from './Groot'
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
Enzyme.configure({ adapter: new Adapter() });
it('works', () => {
const wrap = shallow(
<Groot name='Groot' />
)
expect(wrap.text()).toEqual('I am Groot')
})
My package.json file:
{
"name": "axwayprerequisites",
"homepage": ".",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/core": "^7.12.9",
"@material-ui/core": "^4.11.2",
"axios": "^0.21.1",
"babel-eslint": "^10.1.0",
"bootstrap": "^4.5.3",
"dompurify": "^2.2.0",
"env-cmd": "^10.1.0",
"enzyme": "^3.11.0",
"eslint": "^7.15.0",
"is-regex": "^1.1.2",
"jest-environment-jsdom-sixteen": "^1.0.3",
"jquery": "^3.5.1",
"logrocket": "^1.0.14",
"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-contextmenu": "^2.14.0",
"react-csv": "^2.0.3",
"react-dom": "^17.0.1",
"react-hook-form": "^6.9.6",
"react-scripts": "4.0.0",
"react-select": "^3.1.0",
"react-tabs": "^3.1.1",
"react-test-renderer": "^17.0.1",
"react-three-state-checkbox": "^1.3.4",
"request": "^2.88.2",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"start:local": "env-cmd -f ./.env.local react-scripts start",
"start:testlocal": "env-cmd -f ./.env.testlocal react-scripts start",
"start:test_remoteserver_localclient": "env-cmd -f ./.env.test_remoteserver_localclient react-scripts start",
"test": "react-scripts test --env=jest-environment-jsdom-sixteen",
"eject": "react-scripts eject",
"build": "env-cmd -f ./.env.local react-scripts build",
"build:local": "env-cmd -f ./.env.local react-scripts build",
"build:prod": "env-cmd -f ./.env.prod react-scripts build",
"build:remoteTestServer": "env-cmd -f ./.env.remoteTestServer react-scripts build",
"toto": "env-cmd -f ./.env.toto node toto.js"
},
"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.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@wojtekmaj/enzyme-adapter-react-17": "^0.3.2"
}
}
Has anyone seen this error: Enzyme Internal Error: configured enzyme adapter did not inherit from the EnzymeAdapter base class
Using Enzyme version 3.11.0 and here's my simple setup:
import { configure } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
configure({ adapter: new Adapter() });
I got a dependabot PR encouraging me to bump to 0.6.7, and while I can see the diff, are you able to summarize the changes in a Github release?
Thanks!
While trying to install this in my react 17.0.1 app I got the following in my terminal -
npm WARN ERESOLVE overriding peer dependency
npm WARN Found: react@17.0.1
npm WARN node_modules/react
npm WARN peer react@"*" from @testing-library/react@11.2.2
npm WARN node_modules/@testing-library/react
npm WARN @testing-library/react@"^11.2.2" from the root project
npm WARN 7 more (mini-create-react-context, react-dom, react-redux, ...)
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer react@"0.13.x || 0.14.x || ^15.0.0-0 || ^16.0.0-0" from enzyme-adapter-utils@1.14.0
npm WARN node_modules/enzyme-adapter-utils
npm WARN enzyme-adapter-utils@"^1.14.0" from @wojtekmaj/[email protected]
npm WARN node_modules/@wojtekmaj/enzyme-adapter-react-17
npm ERR! code ERESOLVE
npm ERR! Cannot read property 'length' of undefined
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\shuvr\AppData\Local\npm-cache\_logs\2020-12-18T14_44_23_324Z-debug.log
Hey, I encounter an issue when using chakra-ui
with this library. Here is a reproduction:
https://stackblitz.com/edit/node-mqa7dt?devtoolsheight=33&file=Component.test.js
You can run yarn test
in order to reproduce
Hey, hope all is well.
Hopefully, this is the right place, but feel free to let me know if I am doing something stupid.
So I have attempted to upgrade to react 17, but found all my tests related to useEffect cleanup's are not passing anymore. It would seem like they are triggered.
Example below is an example where the console log never gets called, and the toHaveBeenCalledTimes
is 0.
Here is the test:
it('should call ruleModel.resetState when unmounted', () => {
const resetState = jest.fn()
const ruleModel = {
resetState: action(resetState),
}
const wrapper = renderWrapper({ ruleModel })
wrapper.unmount()
expect(resetState).toHaveBeenCalledTimes(1)
})
And here is the hook:
useEffect(() => {
if (ruleId) getRule(ruleId)
return () => {
console.log('hello')
resetState()
}
}, [ruleId, getRule, resetState])
Here is a snippet of the renderWrapper function:
import { mount, ReactWrapper } from 'enzyme'
const renderWrapper = ({[...]}: any): ReactWrapper => {
const store = createStore({[...]})
return mount(
<StoreProvider store={store}>
<NewRuleConditionsPage
onDiscard={onDiscard}
ruleId={ruleId}
/>
</StoreProvider>
)
}
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/react
npm ERR! peer react@"^17.0.0-0" from @wojtekmaj/[email protected]
npm ERR! node_modules/@wojtekmaj/enzyme-adapter-react-17
npm ERR! dev @wojtekmaj/enzyme-adapter-react-17@"^0.6.7" from the root project
$ node --version
v18.0.0
$ npm --version
8.6.0
My guess is that this is happening due to the -0
on ^17.0.0-0
. Can that be dropped?
Hi, I was blocked by this error after I upgrade react native, jest and enzyme.
FAIL src/features/orders/screens/order-screen/order-rating/order-rating-preview/tests/OrderRatingPreview.spec.js
● Test suite failed to run
rootPath/node_modules/@react-native/polyfills/error-guard.js:14
type ErrorHandler = (error: mixed, isFatal: boolean) => void;
^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/react-native/jest/setup.js:439:6)
Test Suites: 606 failed, 606 total
Tests: 0 total
Snapshots: 0 total
Time: 22.46 s
import 'react-native-gesture-handler/jestSetup';
import { configure, mount, render, shallow } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { NativeModules } from 'react-native';
configure({ adapter: new Adapter() });
"react": "17.0.1",
"react-native": "0.64.2",
"jest": "^27.0.5",
"jest-circus": "^26.6.3",
"jest-expo": "^42.1.0",
"jest-junit": "^12.0.0",
"jest-watch-typeahead": "^0.6.4",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.6.2",
"@wojtekmaj/enzyme-adapter-react-17": "^0.6.3",
"jest": {
"preset": "jest-expo",
"cacheDirectory": "./cache",
"coveragePathIgnorePatterns": [
"index.js",
"./src/globals/*"
],
"moduleFileExtensions": [
"ts",
"tsx",
"jsx",
"js"
],
"testPathIgnorePatterns": [
"./e2e",
"./node_modules/",
"./ios/",
"./android"
],
"setupFiles": [
"./jest/setup.js"
],
"setupFilesAfterEnv": [
"./jest/setupAfterEnv.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.{stories,e2e,spec,d}.*"
],
"coverageDirectory": "./coverage/",
"collectCoverage": false,
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
},
"jest-junit": {
"outputDirectory": "./coverage/jest",
"outputName": "results.xml"
},
I know this may not an enzyme problem, but I really need help to fix it and the issue section of Jest is not friendly with asking question.
Please leave your idea, I appreciate!
Just would like to ask if you have any plans to prepare an adapter for React 18. In my understanding there is small change required in order to get rid of the warning:
console.error
Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot
See the upgrade guide: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis
I have several tests that use mount()
and currently using it.skip
since I've updated to React 17 and this adapter for enzyme. I'm at a loss because I am having to skip a lot of tests that worked with React 16 and enzyme-adapter-react-16. Anything you recommend that I try?
The error I am seeing: (file paths omitted)
The Tests. First one passes and second one fails.
import React from 'react';
import { mount } from 'enzyme';
import RedirectLink from '../index';
jest.mock('react-router-dom');
describe('<RedirectLink />', () => {
let defaultProps: any;
beforeEach(() => {
defaultProps = {
key: 'key',
value: 'value',
};
});
it('should be defined', () => {
expect(<RedirectLink {...defaultProps} />).toBeDefined();
});
it('should render', () => { //TODO: Fix tests for React 17
const wrapper = mount(<RedirectLink {...defaultProps} />);
expect(wrapper).toBeDefined();
});
});
Here's the component code
import React from 'react';
import { Link } from 'react-router-dom';
export interface RedirectLinkProps {
key: string;
value: string;
}
export const RedirectLink: React.FC<RedirectLinkProps> = (key, value) => {
const link = `/some-slug?${key}=${value}`;
return <Link to={link}>{value}</Link>;
};
export default RedirectLink;
I have created a styled-components in a sperate file with the same name and .css.jsx for example Abc.jsx have Abc.css.jsx and it's imported to the Abc.jsx to use. But when I try to test Abc.jsx I get the below error from the mount,
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
I'm using,
React 17
Next.js 11.1
Jest 26.4.2
Enzyme 3.11.0
styled-components 5.3.0
@wojtekmaj/enzyme-adapter-react-17 0.6.2
I keep getting errors following the documentation for setting up Enzyme with the default export, like in #21.
setupEnzyme.ts
import { configure } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
configure({ adapter: new Adapter() });
with packages:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.6",
"react": "^17.0.2",
"react-dom": "^17.0.2",
and the error jest output:
> jest -c jest.config.js --coverage
FAIL src/lib/group.test.ts
● Test suite failed to run
TypeError: enzyme_adapter_react_17_1.default is not a constructor
4 | import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
5 |
> 6 | configure({ adapter: new Adapter() });
| ^
at Object.<anonymous> (setupEnzyme.ts:6:22)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:401:19)
I need to import like below to start jest runs.
import { configure } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17/build/ReactSeventeenAdapter';
configure({ adapter: Adapter });
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.