Write test to check local setState call with jest and testing-react-library










1















I am currently using react-testing-library and can't seem to work out how to test setState for components.



In the following example, I am trying to test that the number of items loaded is correct based on the data from the API. Will later on expand this to test things like the interactions between of the items.



Component:



...

componentDidMount()
this.getModules();


getModules ()
fetch('http://localhost:4000/api/query')
.then(res => res.json())
.then(res => this.setState(data : res.data))
.catch(err => console.error(err))


...

render()
return(
<div data-testid="list">
this.state.data.map((item) =>
return <Item key=item.id data=item/>
)
</div>
)



Test:



...

function renderWithRouter(
ui,
route = '/', history = createMemoryHistory(initialEntries: [route]) = ,)
return
...render(<Router history=history>ui</Router>),
history,



...

test('<ListModule> check list items', () =>
const data = [ ... ]
//not sure what to do here, or after this
const getByTestId = renderWithRouter(<ListModule />)

...

//test the items loaded
expect(getByTestId('list').children.length).toBe(data.length)

//then will continue testing functionality

)


I understand this has to do with jest mock functions, but don't understand how to make them work with setting states, or with simulating an API.



Sample Implementation (working!)



With more practice and learning about making components testable, I was able to get this working. Here is a full example for reference: https://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8



const data = [...]

fetchMock.restore().getOnce('http://localhost:4000/api/query', JSON.stringify(data));

const getByText = renderWithRouter(<ListModule />)

const listItem = await waitForElement(() => getByText('Sample Test Data Title'))









share|improve this question
























  • This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

    – estus
    Nov 14 '18 at 7:17















1















I am currently using react-testing-library and can't seem to work out how to test setState for components.



In the following example, I am trying to test that the number of items loaded is correct based on the data from the API. Will later on expand this to test things like the interactions between of the items.



Component:



...

componentDidMount()
this.getModules();


getModules ()
fetch('http://localhost:4000/api/query')
.then(res => res.json())
.then(res => this.setState(data : res.data))
.catch(err => console.error(err))


...

render()
return(
<div data-testid="list">
this.state.data.map((item) =>
return <Item key=item.id data=item/>
)
</div>
)



Test:



...

function renderWithRouter(
ui,
route = '/', history = createMemoryHistory(initialEntries: [route]) = ,)
return
...render(<Router history=history>ui</Router>),
history,



...

test('<ListModule> check list items', () =>
const data = [ ... ]
//not sure what to do here, or after this
const getByTestId = renderWithRouter(<ListModule />)

...

//test the items loaded
expect(getByTestId('list').children.length).toBe(data.length)

//then will continue testing functionality

)


I understand this has to do with jest mock functions, but don't understand how to make them work with setting states, or with simulating an API.



Sample Implementation (working!)



With more practice and learning about making components testable, I was able to get this working. Here is a full example for reference: https://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8



const data = [...]

fetchMock.restore().getOnce('http://localhost:4000/api/query', JSON.stringify(data));

const getByText = renderWithRouter(<ListModule />)

const listItem = await waitForElement(() => getByText('Sample Test Data Title'))









share|improve this question
























  • This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

    – estus
    Nov 14 '18 at 7:17













1












1








1








I am currently using react-testing-library and can't seem to work out how to test setState for components.



In the following example, I am trying to test that the number of items loaded is correct based on the data from the API. Will later on expand this to test things like the interactions between of the items.



Component:



...

componentDidMount()
this.getModules();


getModules ()
fetch('http://localhost:4000/api/query')
.then(res => res.json())
.then(res => this.setState(data : res.data))
.catch(err => console.error(err))


...

render()
return(
<div data-testid="list">
this.state.data.map((item) =>
return <Item key=item.id data=item/>
)
</div>
)



Test:



...

function renderWithRouter(
ui,
route = '/', history = createMemoryHistory(initialEntries: [route]) = ,)
return
...render(<Router history=history>ui</Router>),
history,



...

test('<ListModule> check list items', () =>
const data = [ ... ]
//not sure what to do here, or after this
const getByTestId = renderWithRouter(<ListModule />)

...

//test the items loaded
expect(getByTestId('list').children.length).toBe(data.length)

//then will continue testing functionality

)


I understand this has to do with jest mock functions, but don't understand how to make them work with setting states, or with simulating an API.



Sample Implementation (working!)



With more practice and learning about making components testable, I was able to get this working. Here is a full example for reference: https://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8



const data = [...]

fetchMock.restore().getOnce('http://localhost:4000/api/query', JSON.stringify(data));

const getByText = renderWithRouter(<ListModule />)

const listItem = await waitForElement(() => getByText('Sample Test Data Title'))









share|improve this question
















I am currently using react-testing-library and can't seem to work out how to test setState for components.



In the following example, I am trying to test that the number of items loaded is correct based on the data from the API. Will later on expand this to test things like the interactions between of the items.



Component:



...

componentDidMount()
this.getModules();


getModules ()
fetch('http://localhost:4000/api/query')
.then(res => res.json())
.then(res => this.setState(data : res.data))
.catch(err => console.error(err))


...

render()
return(
<div data-testid="list">
this.state.data.map((item) =>
return <Item key=item.id data=item/>
)
</div>
)



Test:



...

function renderWithRouter(
ui,
route = '/', history = createMemoryHistory(initialEntries: [route]) = ,)
return
...render(<Router history=history>ui</Router>),
history,



...

test('<ListModule> check list items', () =>
const data = [ ... ]
//not sure what to do here, or after this
const getByTestId = renderWithRouter(<ListModule />)

...

//test the items loaded
expect(getByTestId('list').children.length).toBe(data.length)

//then will continue testing functionality

)


I understand this has to do with jest mock functions, but don't understand how to make them work with setting states, or with simulating an API.



Sample Implementation (working!)



With more practice and learning about making components testable, I was able to get this working. Here is a full example for reference: https://gist.github.com/alfonsomunozpomer/de992a9710724eb248be3842029801c8



const data = [...]

fetchMock.restore().getOnce('http://localhost:4000/api/query', JSON.stringify(data));

const getByText = renderWithRouter(<ListModule />)

const listItem = await waitForElement(() => getByText('Sample Test Data Title'))






javascript reactjs jestjs react-router-dom react-testing-library






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 22 at 1:50







Charklewis

















asked Nov 13 '18 at 21:54









CharklewisCharklewis

5318




5318












  • This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

    – estus
    Nov 14 '18 at 7:17

















  • This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

    – estus
    Nov 14 '18 at 7:17
















This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

– estus
Nov 14 '18 at 7:17





This is exactly same problem, stackoverflow.com/questions/52767157/… . getModules doesn't return a promise that could be chained in tests. fetch should be mocked, as the answer suggests.

– estus
Nov 14 '18 at 7:17












1 Answer
1






active

oldest

votes


















2














You should avoid testing setState directly since that is an implementation detail of the component. You are on the right path to testing that the correct number of items are rendered. You can mock the fetch function by either replacing window.fetch with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.



// Note that this method does not build the full response object like status codes, headers, etc.
window.fetch = jest.fn(() =>
return Promise.resolve(
json: () => Promise.resolve(fakeData),
);
);


OR



import fetchMock from "fetch-mock";
fetchMock.get(url, fakeData);





share|improve this answer






















    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%2f53290085%2fwrite-test-to-check-local-setstate-call-with-jest-and-testing-react-library%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You should avoid testing setState directly since that is an implementation detail of the component. You are on the right path to testing that the correct number of items are rendered. You can mock the fetch function by either replacing window.fetch with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.



    // Note that this method does not build the full response object like status codes, headers, etc.
    window.fetch = jest.fn(() =>
    return Promise.resolve(
    json: () => Promise.resolve(fakeData),
    );
    );


    OR



    import fetchMock from "fetch-mock";
    fetchMock.get(url, fakeData);





    share|improve this answer



























      2














      You should avoid testing setState directly since that is an implementation detail of the component. You are on the right path to testing that the correct number of items are rendered. You can mock the fetch function by either replacing window.fetch with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.



      // Note that this method does not build the full response object like status codes, headers, etc.
      window.fetch = jest.fn(() =>
      return Promise.resolve(
      json: () => Promise.resolve(fakeData),
      );
      );


      OR



      import fetchMock from "fetch-mock";
      fetchMock.get(url, fakeData);





      share|improve this answer

























        2












        2








        2







        You should avoid testing setState directly since that is an implementation detail of the component. You are on the right path to testing that the correct number of items are rendered. You can mock the fetch function by either replacing window.fetch with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.



        // Note that this method does not build the full response object like status codes, headers, etc.
        window.fetch = jest.fn(() =>
        return Promise.resolve(
        json: () => Promise.resolve(fakeData),
        );
        );


        OR



        import fetchMock from "fetch-mock";
        fetchMock.get(url, fakeData);





        share|improve this answer













        You should avoid testing setState directly since that is an implementation detail of the component. You are on the right path to testing that the correct number of items are rendered. You can mock the fetch function by either replacing window.fetch with a Jest mock function or using the fetch-mock library to handle the heavy lifting for you.



        // Note that this method does not build the full response object like status codes, headers, etc.
        window.fetch = jest.fn(() =>
        return Promise.resolve(
        json: () => Promise.resolve(fakeData),
        );
        );


        OR



        import fetchMock from "fetch-mock";
        fetchMock.get(url, fakeData);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 14 '18 at 0:05









        TylerTyler

        1,02627




        1,02627



























            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%2f53290085%2fwrite-test-to-check-local-setstate-call-with-jest-and-testing-react-library%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







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3

            Museum of Modern and Contemporary Art of Trento and Rovereto