I'm starting learning React and while I was doing some tests i noticed two warning messages:
Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.
Warning: Shallow renderer has been moved to react-test-renderer/shallow. Update references to remove this warning.
They don't prevent the tests from running nor from properly validating, but there is always this error.
By looking at the docs, I found this page, even after I included those lines they recommend, the warning message is still showing up.
I'm trying a very simple test to start with, this is my code:
import React from "react";
import toJson from "enzyme-to-json";
import { shallow } from "enzyme";
import { About } from "./About";
describe('Rendering test', () => {
const component = shallow(<About />);
const tree = toJson(component);
it('Should render the About component', () => {
expect(tree).toMatchSnapshot();
})
it('Should not contain an h2 element', () => {
expect( component.contains('h2') ).toBe(false);
})
})
What do I need to do in order to solve this warnings? I already updated all my packaged to the latest versions.
If you are using React 0.14 or React <15.5, in addition to enzyme, you will have to ensure that you also have the following npm modules installed if they were not already:
npm i --save-dev react-addons-test-utils react-dom
If you are using React >=15.5, in addition to enzyme, you will have to ensure that you also have the following npm modules installed if they were not already:
npm i --save-dev react-test-renderer react-dom
I think it's coming from using the shallow render function from enzyme, which has not been updated for v15.5 yet (there is a pull request for it though).
You can try to use one of the other render function (render or mount), but this will change the semantics of your test (and may or may not still produce the warning).
Your other option is to not use enzyme and use react-test-renderer/shallow yourself, but the enzyme API is quite nice for testing components.
My advice is to wait for the version of enzyme and just live with the warning for now.
Update August of 2017
If you install react-test-renderer it will work but all react-* versions should match:
e.g.
react#15.4.2
react-test-renderer#15.4.2
react-dom#15.4.2
react-addons-test-utils#15.4.2
In my environment, only this config worked!
I was still receiving the following warning after trying steps listed above.
Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.
Updating the path in \node_modules\react-addons-test-utils\index.js solved this for me.
Old:
lowPriorityWarning(
false,
'ReactTestUtils has been moved to react-dom/test-utils. ' +
'Update references to remove this warning.'
);
module.exports = require('react-dom/lib/ReactTestUtils');
New:
lowPriorityWarning(
false,
'ReactTestUtils has been moved to react-dom/test-utils. ' +
'Update references to remove this warning.'
);
module.exports = require('react-dom/test-utils');
Related
I'm testinng a react component using the RTL, and everytime I ran a test, I get,
"messageParent" can only be used inside a worker
**Here's the code
describe('Header', () => {
it('validates header component is rendered', () => {
const { getByTestId } = render(<Header patientName="Jake Bland" />);
expect(getByTestId('patient-name')).toHaveTextContent(/^Jake Bland$/);
expect(getByTestId('dateRange')).toBe(dateRange);
});
});
Any help on this will be greatly appreciated.
I was having the same issue, and it was caused by calling toBe() or toEqual() on an HTMLElement. So your most likely culprit is here, since getByTestId returns an HTMLElement:
expect(getByTestId('dateRange')).toBe(dateRange);
I fixed my issue by testing against the element's text content instead.
expect(getByTestId('dateRange')).toHaveTextContent('...');
Hi I had the same issue after spending some time googling around i found this: github issues forum
it turned out that this issue is caused by node12 version i downgraded my one to version 10 and everything worked i have also upgraded to version 14 and that also works.
check what is yours node version in ur terminal:
node -v if (version 12) upgrade it!
nvm install v14.8.0 (something like this or the leates one)
nvm use v14.8.0 (or any other version you may wish to install that is above 12)
hopefully this helps
I ran into this error while testing to see if a <select> had the right number of options, when using this:
expect(container.querySelectorAll('option')).toBe(2);
#testing-library/react must be trying to do something strange to get the length of the HTML collection, I have. So I added .length to the query:
expect(container.querySelectorAll('option').length).toBe(2);
All was well.
I had the same bug but I was able to fix it by importing '#testing-library/jest-dom' as follows in my test file:
import '#testing-library/jest-dom'
It turned out that the package above is a peerDependency for '#testing-library/react'. Thus the error.
I am trying to get the wordpress block editor to load in a react project: https://www.npmjs.com/package/#wordpress/block-editor.
I have set it up exactly as per the example on the npm page but it gives an invalid hook error. I think perhaps it is due to a version mismatch as error suggest?
This is the code:
import {
BlockEditorProvider,
BlockList,
WritingFlow,
ObserveTyping
} from "#wordpress/block-editor";
import { SlotFillProvider, Popover } from "#wordpress/components";
import { useState } from "#wordpress/element";
import "#wordpress/components/build-style/style.css";
import "#wordpress/block-editor/build-style/style.css";
export default function MyEditorComponent() {
const [blocks, updateBlocks] = useState([]);
return (
<BlockEditorProvider
value={blocks}
onInput={(blocks) => updateBlocks(blocks)}
onChange={(blocks) => updateBlocks(blocks)}
>
<SlotFillProvider>
<Popover.Slot name="block-toolbar" />
<WritingFlow>
<ObserveTyping>
<BlockList />
</ObserveTyping>
</WritingFlow>
<Popover.Slot />
</SlotFillProvider>
</BlockEditorProvider>
);
}
And the typical hook error:
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 [link] for tips about how to debug and fix this problem.
I have setup a codepen to tyr it here: https://codesandbox.io/s/sleepy-proskuriakova-op59q
I looked up wordpress version of react and it seems to be 16.6.3 so set that in sandbox and used an older version of react scripts (2.1.8) that at the time was using 16.6.2 but no change in error. I tried several combinations of versions with no change.
What is actually causing this error? How can I get this component to load?
Here is a working codesandbox.
Things I've changed:
react and react-dom to 16.13.1 which is the version used in #wordpress/element
Had to add DropZoneProvider
Install #wordpress/block-library and call registerCoreBlocks
For more code examples you can check the official storybook docs, the source code is in the bottom panel, under the Story tab.
I have a container in react-native that is importing the typical kind of function that we usually store at utils directory such as capitaliseWord() or whatever.
One of the functions of that utils module uses t, so we import i18n inside that utils folder in order to be able to use t
We use languageDetector inside our i18n to detect the user's mobile language. Because languageDetector needs deviceLocale (e.g UK, US, NL, etc), and Jest runs on a different context, if I try to do test the container, I will get Cannot read property 'deviceLocale' of undefined.
So I created a manual __mocks__ directory (as https://jestjs.io/docs/en/manual-mocks#mocking-user-modules states) and I created my own i18n that just injects the deviceLocale string manually, in order to be able to run the tests.
Turns out the test ignores the __mocks__/i18n and points directly to the original one... Any ideas of what it could go wrong?
And my jest config inside package.json
https://gist.github.com/e00dd4ee41b06265632d3bcfe76e7cb0
original i18n.js
https://gist.github.com/pavilion/3c48c6017a82356914f0ad69d7251496
mocked i18n.js
https://gist.github.com/pavilion/17e322340581fb948ed7e319ae4a5ac9 (notice the detect key inside languageDetector has been manually mocked)
Component to be tested
https://gist.github.com/pavilion/20dc0c5b1a6d2ee709b7a71ec7b819c1
utils.js
https://gist.github.com/pavilion/1c5df0f71d50462d75234365ae1e4aaf
Comp.test.js
https://gist.github.com/pavilion/2a84880bee3a99fa51fc3e28cfa8f913
Error:
https://gist.github.com/pavilion/012ee0889ebbe2b93b2108d93543e19c
I think the problem is not in the mock, but the import! Try this time requiring the component in the test, after the mock has been injected:
import React from 'react';
import { shallow } from 'enzyme';
jest.mock('../../config/i18n');
describe('<Comp />', () => {
it('must match the snapshot', () => {
// Require here instead of importing on top
const Comp = require("./Comp").default;
// state and props properly set up
const wrapper = shallow(<Comp />);
expect(wrapper).toMatchSnapshot();
});
});
I tried this locally and it's working fine: the module gets mocked. I simplified a lot my example so perhaps you run into some new error but technically this should solve your problem.
EDIT: pushed my working example to github here in case it's for any help.
I'm using karma-webpack and I am refactoring a React Component to use in multiple places. I moved the component
to it's own file, so I can import it and connect it differently by applying mapStateToProps / mapDispatchToProps in the HOC I later include on my page.
Here's the scenario:
EventTable - imports EventTableComponent, exports connected / wrapped component
MyEventTable - imports EventTableComponent, exports connected / wrapped component
EventTableComponent - defines the props / behaviors shared to render the data rows
When I git mv EventTable to EventTableComponent and refactored the code so the connected stuff is in the HOCs, the tests start failing to import EventTableComponent only in karma-webpack. Chrome works just fine and the view render perfectly. QA is happy, or would be, but my build fails.
The build is failing because WrappedComponent is undefined for the EventTable and MyEventTable components, which causes connect to throw the message in the synopsis (cannot read displayName of undefined), but I don't even import either of these files into my test! Instead, it fails while karma webpack is building, but before running any tests.
I fixed the build locally by destroying the view and making a "fake" / "replacement" like this:
function EventTableComponent () {
return (<div>garbage here</div>);
}
The build passes.
The most confusing part in all of this? I don't even test the HOC at all. I import just the EventTableComponent into the test, but karma-webpack, as suggested in the Redux Documentation.
I've written a minimal example gist to illustrate:
https://gist.github.com/zedd45/cbc981e385dc33d6920d7fcb55e7a3e0
I was able to solve this by tricking the module system.
// EventTableComponentWrapper.jsx
import EventTableComponent from './EventTableComponent';
if (process.env.NODE_ENV === 'test') {
module.exports = require('./EventTableComponent.test.jsx');
} else {
module.exports = EventTableComponent;
}
I import this file in both HOC Components, and based on my environment variable, I get the right one, and Karma Webpack is tricked into not exploding.
I arrived at this conclusion based on a few leads, but credit goes to this SO Post:
Conditional build based on environment using Webpack
and also to Wout Mertens from the Webpack Gitter channel for tipping me off to the issue being ES6 Class Import / Export related.
Simple example:
import * as React from 'react'
declare function getFish(x: any): any;
declare var Tank: any;
var Aquarium = ({species}) => (
<Tank>
{getFish(species)}
</Tank>
);
let x = <Aquarium species="rainbowfish"/>;
Result:
(10,9): error TS2605: JSX element type 'Element' is not a constructor function for JSX elements.
Note the error is in regards to the usage of the Component (let x declaration). It seems as if maybe the definition file for React is not allowing this as a valid JSX? I am using the latest React 0.14 definition file from tsd, what am I doing wrong?
Say I have defined the following stateless functional component (React v0.14)
let GreeterComponent = (props: {name: string}){
return <div>Hi {props.name}!</div>
}
in a different component, I am using it like this:
class WrappingComponent extends React.Component{
render(){
let names = ['tom', 'john', 'simon'];
return (
<div className="names">
{names.map((name)=> <GreeterComponent name={name} />)}
</div>
);
}
}
I am getting this error from typescript compiler:
error TS2605: JSX element type 'Element' is not a constructor function
for JSX elements. Property 'render' is missing in type 'Element'.
How can I fix it? What is the correct to work with stateless functional components in typescript? I am using the latest react.d.ts from tsd
When you define a stateless component, it's a plain and simple function.
When you instantiate it (i.e. pass it to React.createElement), it gets wrapped with React.StatelessComponent.
error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. Property 'render' is missing in type 'Element'.
That will work fine in TypeScript latest npm install typescript#latest.
I had to install the typescript using #next:
npm install typescript#next --save-dev
At the moment of this answer, the #next version is 1.9.0-dev.20160217.
In the beginning I though the problem was with the react.d.ts or react-dom.d.ts... but it was not. The latest version of these are already installed here. But the real problem was I installed typescript version 1.7.5, the latest release.
Some notes about this: as per the blog post Using typescript#next nightly package? Don’t rely on –save-dev to be up-to-date!, you cannot rely on npm updating your dependency of typescript to a greater version number after installing with #next and --save-dev.
As they explain, npm update seems not to update from one beta version to the next:
e.g. The dependency string "^1.6.0-dev.20150818" (inside the package.json) will have the package updated to 1.6.0-dev.20150825, but not to 1.7.0-dev.20150901 when running npm update
What they recommend is to change the dependency string that npm --save-dev saved inside your package.json to just "next" to be always with the latest of the latest version:
{
...
"devDependencies": {
...
"typescript": "next",
...
}
}
I personally didn't try it, because I like to have full control over the version I am using. I rarely run npm update anyway.