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










0















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.










share|improve this question



















  • 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











  • 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 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















0















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.










share|improve this question



















  • 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











  • 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 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













0












0








0








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.










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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 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











  • 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 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












  • 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











  • 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 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







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












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
);



);













draft saved

draft discarded


















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















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme