Testing React components that fetches data using Hooks2019 Community Moderator ElectionLoop inside React JSXProgrammatically navigate using react routerHow can I get Enzyme to recognise the react-html-attrs plugin?State is undefined when simulating click in react component testreact-native mount component without enzymeWarning: Shallow renderer has been moved to react-test-renderer/shallowHow to unit test an api call and assert state change in react and enzyme?Concerns about performance with the solution found using React hooksReact Hooks: Lazy Loading Breaks useLayoutEffect?state is not being updated when using React Hooks
Print a physical multiplication table
How to get the n-th line after a grepped one?
Python if-else code style for reduced code for rounding floats
Different outputs for `w`, `who`, `whoami` and `id`
How are passwords stolen from companies if they only store hashes?
New passport but visa is in old (lost) passport
How to terminate ping <dest> &
PTIJ: Who should I vote for? (21st Knesset Edition)
et qui - how do you really understand that kind of phraseology?
Are Roman Catholic priests ever addressed as pastor
Is it insecure to send a password in a `curl` command?
Does multi-classing into Fighter give you heavy armor?
Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?
About the actual radiative impact of greenhouse gas emission over time
Knife as defense against stray dogs
Why do tuner card drivers fail to build after kernel update to 4.4.0-143-generic?
How do I hide Chekhov's Gun?
Could the Saturn V actually have launched astronauts around Venus?
Is there a place to find the pricing for things not mentioned in the PHB? (non-magical)
Is it true that good novels will automatically sell themselves on Amazon (and so on) and there is no need for one to waste time promoting?
This word with a lot of past tenses
If I am holding an item before I cast Blink, will it move with me through the Ethereal Plane?
When to use a slotted vs. solid turner?
How to write cleanly even if my character uses expletive language?
Testing React components that fetches data using Hooks
2019 Community Moderator ElectionLoop inside React JSXProgrammatically navigate using react routerHow can I get Enzyme to recognise the react-html-attrs plugin?State is undefined when simulating click in react component testreact-native mount component without enzymeWarning: Shallow renderer has been moved to react-test-renderer/shallowHow to unit test an api call and assert state change in react and enzyme?Concerns about performance with the solution found using React hooksReact Hooks: Lazy Loading Breaks useLayoutEffect?state is not being updated when using React Hooks
My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount()
was the place to go. But now I wanted to use hooks for this.
const App = () =>
const [ state, setState ] = useState(0);
useEffect(() =>
fetchData().then(setState);
);
return (
<div>... data display ...</div>
);
;
And my test using Jest and Enzyme looks like this:
import React from 'react';
import mount from 'enzyme';
import App from './App';
import act from 'react-test-renderer';
jest.mock('./api');
import fetchData from './api';
describe('<App />', () =>
it('renders without crashing', (done) =>
fetchData.mockImplementation(() =>
return Promise.resolve(42);
);
act(() => mount(<App />));
setTimeout(() =>
// expectations here
done();
, 500);
);
);
The test succeeds, but it logs a few warnings:
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() =>
/* fire events that update state */
);
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at (redacted)
in App (created by WrapperComponent)
in WrapperComponent
The only update to the App component happens from the Promise callback. How can I ensure this happens within the act
block? The docs clearly suggest to have assertions happen outside the act
block. Besides, putting them inside doesn't change the warning.
reactjs jestjs enzyme react-hooks react-test-renderer
add a comment |
My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount()
was the place to go. But now I wanted to use hooks for this.
const App = () =>
const [ state, setState ] = useState(0);
useEffect(() =>
fetchData().then(setState);
);
return (
<div>... data display ...</div>
);
;
And my test using Jest and Enzyme looks like this:
import React from 'react';
import mount from 'enzyme';
import App from './App';
import act from 'react-test-renderer';
jest.mock('./api');
import fetchData from './api';
describe('<App />', () =>
it('renders without crashing', (done) =>
fetchData.mockImplementation(() =>
return Promise.resolve(42);
);
act(() => mount(<App />));
setTimeout(() =>
// expectations here
done();
, 500);
);
);
The test succeeds, but it logs a few warnings:
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() =>
/* fire events that update state */
);
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at (redacted)
in App (created by WrapperComponent)
in WrapperComponent
The only update to the App component happens from the Promise callback. How can I ensure this happens within the act
block? The docs clearly suggest to have assertions happen outside the act
block. Besides, putting them inside doesn't change the warning.
reactjs jestjs enzyme react-hooks react-test-renderer
1
This code will callfetchData
twice or go to an infinite loop iffetchData
returns different data. You should pass[]
as second argument touseEffect
to emaulatecomponentDidMount
. OtherwiseuseEffect
will be called on every render. FirstfetchData
causes a rerender. And it will cause additional renders wheneversetState
gets a new value.
– UjinT34
Mar 7 at 15:48
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
Thanks @UjinT34 for the remark. In fact, I had[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invokingfetchData
too often. Still, the warning about not usingact
is there :(
– mthmulders
Mar 8 at 7:18
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside anact
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outsideact
, thus triggering the warning. But I don't know how to fix that.
– mthmulders
Mar 8 at 7:22
add a comment |
My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount()
was the place to go. But now I wanted to use hooks for this.
const App = () =>
const [ state, setState ] = useState(0);
useEffect(() =>
fetchData().then(setState);
);
return (
<div>... data display ...</div>
);
;
And my test using Jest and Enzyme looks like this:
import React from 'react';
import mount from 'enzyme';
import App from './App';
import act from 'react-test-renderer';
jest.mock('./api');
import fetchData from './api';
describe('<App />', () =>
it('renders without crashing', (done) =>
fetchData.mockImplementation(() =>
return Promise.resolve(42);
);
act(() => mount(<App />));
setTimeout(() =>
// expectations here
done();
, 500);
);
);
The test succeeds, but it logs a few warnings:
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() =>
/* fire events that update state */
);
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at (redacted)
in App (created by WrapperComponent)
in WrapperComponent
The only update to the App component happens from the Promise callback. How can I ensure this happens within the act
block? The docs clearly suggest to have assertions happen outside the act
block. Besides, putting them inside doesn't change the warning.
reactjs jestjs enzyme react-hooks react-test-renderer
My React-application has a component that fetches data to display from a remote server. In the pre-hooks era, componentDidMount()
was the place to go. But now I wanted to use hooks for this.
const App = () =>
const [ state, setState ] = useState(0);
useEffect(() =>
fetchData().then(setState);
);
return (
<div>... data display ...</div>
);
;
And my test using Jest and Enzyme looks like this:
import React from 'react';
import mount from 'enzyme';
import App from './App';
import act from 'react-test-renderer';
jest.mock('./api');
import fetchData from './api';
describe('<App />', () =>
it('renders without crashing', (done) =>
fetchData.mockImplementation(() =>
return Promise.resolve(42);
);
act(() => mount(<App />));
setTimeout(() =>
// expectations here
done();
, 500);
);
);
The test succeeds, but it logs a few warnings:
console.error node_modules/react-dom/cjs/react-dom.development.js:506
Warning: An update to App inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() =>
/* fire events that update state */
);
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser. Learn more at (redacted)
in App (created by WrapperComponent)
in WrapperComponent
The only update to the App component happens from the Promise callback. How can I ensure this happens within the act
block? The docs clearly suggest to have assertions happen outside the act
block. Besides, putting them inside doesn't change the warning.
reactjs jestjs enzyme react-hooks react-test-renderer
reactjs jestjs enzyme react-hooks react-test-renderer
edited Mar 7 at 15:40
skyboyer
4,08311230
4,08311230
asked Mar 7 at 15:35
mthmuldersmthmulders
7,33411741
7,33411741
1
This code will callfetchData
twice or go to an infinite loop iffetchData
returns different data. You should pass[]
as second argument touseEffect
to emaulatecomponentDidMount
. OtherwiseuseEffect
will be called on every render. FirstfetchData
causes a rerender. And it will cause additional renders wheneversetState
gets a new value.
– UjinT34
Mar 7 at 15:48
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
Thanks @UjinT34 for the remark. In fact, I had[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invokingfetchData
too often. Still, the warning about not usingact
is there :(
– mthmulders
Mar 8 at 7:18
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside anact
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outsideact
, thus triggering the warning. But I don't know how to fix that.
– mthmulders
Mar 8 at 7:22
add a comment |
1
This code will callfetchData
twice or go to an infinite loop iffetchData
returns different data. You should pass[]
as second argument touseEffect
to emaulatecomponentDidMount
. OtherwiseuseEffect
will be called on every render. FirstfetchData
causes a rerender. And it will cause additional renders wheneversetState
gets a new value.
– UjinT34
Mar 7 at 15:48
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
Thanks @UjinT34 for the remark. In fact, I had[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invokingfetchData
too often. Still, the warning about not usingact
is there :(
– mthmulders
Mar 8 at 7:18
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside anact
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outsideact
, thus triggering the warning. But I don't know how to fix that.
– mthmulders
Mar 8 at 7:22
1
1
This code will call
fetchData
twice or go to an infinite loop if fetchData
returns different data. You should pass []
as second argument to useEffect
to emaulate componentDidMount
. Otherwise useEffect
will be called on every render. First fetchData
causes a rerender. And it will cause additional renders whenever setState
gets a new value.– UjinT34
Mar 7 at 15:48
This code will call
fetchData
twice or go to an infinite loop if fetchData
returns different data. You should pass []
as second argument to useEffect
to emaulate componentDidMount
. Otherwise useEffect
will be called on every render. First fetchData
causes a rerender. And it will cause additional renders whenever setState
gets a new value.– UjinT34
Mar 7 at 15:48
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
Thanks @UjinT34 for the remark. In fact, I had
[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invoking fetchData
too often. Still, the warning about not using act
is there :(– mthmulders
Mar 8 at 7:18
Thanks @UjinT34 for the remark. In fact, I had
[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invoking fetchData
too often. Still, the warning about not using act
is there :(– mthmulders
Mar 8 at 7:18
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside an
act
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outside act
, thus triggering the warning. But I don't know how to fix that.– mthmulders
Mar 8 at 7:22
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside an
act
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outside act
, thus triggering the warning. But I don't know how to fix that.– mthmulders
Mar 8 at 7:22
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047535%2ftesting-react-components-that-fetches-data-using-hooks%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55047535%2ftesting-react-components-that-fetches-data-using-hooks%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
This code will call
fetchData
twice or go to an infinite loop iffetchData
returns different data. You should pass[]
as second argument touseEffect
to emaulatecomponentDidMount
. OtherwiseuseEffect
will be called on every render. FirstfetchData
causes a rerender. And it will cause additional renders wheneversetState
gets a new value.– UjinT34
Mar 7 at 15:48
github.com/kentcdodds/react-testing-library/issues/… seems like such cases are under discussion
– skyboyer
Mar 7 at 15:54
I'm not sure but github.com/threepointone/react-act-examples looks promising
– skyboyer
Mar 7 at 16:03
Thanks @UjinT34 for the remark. In fact, I had
[]
as deps, but figured it wasn't relevant for this particular question. Indeed, it should be there to prevent invokingfetchData
too often. Still, the warning about not usingact
is there :(– mthmulders
Mar 8 at 7:18
Thanks for the suggestion @skyboyer. The point with the repo you refer to is that they use "manual" mocks, which they can manually resolve - inside an
act
statement. I prefer to use Jests mocking possibilities instead. My feeling is that resolving the Promise from the Jest mock happens outsideact
, thus triggering the warning. But I don't know how to fix that.– mthmulders
Mar 8 at 7:22