Jest - How to test output of react methods is correct?












2














I am having problems trying to understand how I can use Jest to test the output of a method in a react file. I am completely new to this style of web development so any help is appreciated.



I have a js file like this:



import * as React from 'react';
import 'es6-promise';
import 'isomorphic-fetch';

export default class FetchData extends React.Component {
constructor() {
super();
this.state = { documents: , loading: true };
fetch('api/SampleData/GetDocuments')
.then(response => response.json())
.then(data => {
this.setState({ documents: data, loading: false });
});
}

render() {
let contents = this.state.loading ? <p><em>Loading...</em></p>
: FetchData.renderdocumentsTable(this.state.documents);

return <div>
<button onClick={() => { this.refreshData() }}>Refresh</button>
<p>This component demonstrates bad document data from the server.</p>
{contents}
</div>;
}

refreshData() {
fetch('api/SampleData/GetDocuments')
.then(response => response.json())
.then(data => {
this.setState({ documents: data, loading: false });
});
}

static renderdocumentsTable(documents) {
return <table className='table'>
<thead>
<tr>
<th>Filename</th>
<th>CurrentSite</th>
<th>CorrectSite</th>
</tr>
</thead>
<tbody>
{documents.map(document =>
<tr className="document-row" key={document.documentId}>
<td>{document.filename}</td>
<td>{document.currentSite}</td>
<td>{document.correctSite}</td>
</tr>
)}
</tbody>
</table>;
}
}


I basically want to be able to test that a table is returned with the correct number of columns however I can't work out exactly how to do this with Jest.



Thanks,
Alex










share|improve this question



























    2














    I am having problems trying to understand how I can use Jest to test the output of a method in a react file. I am completely new to this style of web development so any help is appreciated.



    I have a js file like this:



    import * as React from 'react';
    import 'es6-promise';
    import 'isomorphic-fetch';

    export default class FetchData extends React.Component {
    constructor() {
    super();
    this.state = { documents: , loading: true };
    fetch('api/SampleData/GetDocuments')
    .then(response => response.json())
    .then(data => {
    this.setState({ documents: data, loading: false });
    });
    }

    render() {
    let contents = this.state.loading ? <p><em>Loading...</em></p>
    : FetchData.renderdocumentsTable(this.state.documents);

    return <div>
    <button onClick={() => { this.refreshData() }}>Refresh</button>
    <p>This component demonstrates bad document data from the server.</p>
    {contents}
    </div>;
    }

    refreshData() {
    fetch('api/SampleData/GetDocuments')
    .then(response => response.json())
    .then(data => {
    this.setState({ documents: data, loading: false });
    });
    }

    static renderdocumentsTable(documents) {
    return <table className='table'>
    <thead>
    <tr>
    <th>Filename</th>
    <th>CurrentSite</th>
    <th>CorrectSite</th>
    </tr>
    </thead>
    <tbody>
    {documents.map(document =>
    <tr className="document-row" key={document.documentId}>
    <td>{document.filename}</td>
    <td>{document.currentSite}</td>
    <td>{document.correctSite}</td>
    </tr>
    )}
    </tbody>
    </table>;
    }
    }


    I basically want to be able to test that a table is returned with the correct number of columns however I can't work out exactly how to do this with Jest.



    Thanks,
    Alex










    share|improve this question

























      2












      2








      2







      I am having problems trying to understand how I can use Jest to test the output of a method in a react file. I am completely new to this style of web development so any help is appreciated.



      I have a js file like this:



      import * as React from 'react';
      import 'es6-promise';
      import 'isomorphic-fetch';

      export default class FetchData extends React.Component {
      constructor() {
      super();
      this.state = { documents: , loading: true };
      fetch('api/SampleData/GetDocuments')
      .then(response => response.json())
      .then(data => {
      this.setState({ documents: data, loading: false });
      });
      }

      render() {
      let contents = this.state.loading ? <p><em>Loading...</em></p>
      : FetchData.renderdocumentsTable(this.state.documents);

      return <div>
      <button onClick={() => { this.refreshData() }}>Refresh</button>
      <p>This component demonstrates bad document data from the server.</p>
      {contents}
      </div>;
      }

      refreshData() {
      fetch('api/SampleData/GetDocuments')
      .then(response => response.json())
      .then(data => {
      this.setState({ documents: data, loading: false });
      });
      }

      static renderdocumentsTable(documents) {
      return <table className='table'>
      <thead>
      <tr>
      <th>Filename</th>
      <th>CurrentSite</th>
      <th>CorrectSite</th>
      </tr>
      </thead>
      <tbody>
      {documents.map(document =>
      <tr className="document-row" key={document.documentId}>
      <td>{document.filename}</td>
      <td>{document.currentSite}</td>
      <td>{document.correctSite}</td>
      </tr>
      )}
      </tbody>
      </table>;
      }
      }


      I basically want to be able to test that a table is returned with the correct number of columns however I can't work out exactly how to do this with Jest.



      Thanks,
      Alex










      share|improve this question













      I am having problems trying to understand how I can use Jest to test the output of a method in a react file. I am completely new to this style of web development so any help is appreciated.



      I have a js file like this:



      import * as React from 'react';
      import 'es6-promise';
      import 'isomorphic-fetch';

      export default class FetchData extends React.Component {
      constructor() {
      super();
      this.state = { documents: , loading: true };
      fetch('api/SampleData/GetDocuments')
      .then(response => response.json())
      .then(data => {
      this.setState({ documents: data, loading: false });
      });
      }

      render() {
      let contents = this.state.loading ? <p><em>Loading...</em></p>
      : FetchData.renderdocumentsTable(this.state.documents);

      return <div>
      <button onClick={() => { this.refreshData() }}>Refresh</button>
      <p>This component demonstrates bad document data from the server.</p>
      {contents}
      </div>;
      }

      refreshData() {
      fetch('api/SampleData/GetDocuments')
      .then(response => response.json())
      .then(data => {
      this.setState({ documents: data, loading: false });
      });
      }

      static renderdocumentsTable(documents) {
      return <table className='table'>
      <thead>
      <tr>
      <th>Filename</th>
      <th>CurrentSite</th>
      <th>CorrectSite</th>
      </tr>
      </thead>
      <tbody>
      {documents.map(document =>
      <tr className="document-row" key={document.documentId}>
      <td>{document.filename}</td>
      <td>{document.currentSite}</td>
      <td>{document.correctSite}</td>
      </tr>
      )}
      </tbody>
      </table>;
      }
      }


      I basically want to be able to test that a table is returned with the correct number of columns however I can't work out exactly how to do this with Jest.



      Thanks,
      Alex







      reactjs jestjs babel-jest






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 '18 at 14:40









      Alex Harvey

      790319




      790319
























          1 Answer
          1






          active

          oldest

          votes


















          2














          I follow next approach:





          1. Mocking dependencies called explicitly by component under test.

          2. Initializing component with shallow()

          3. trying different modifications

          4. Checking component with .toMatchSnapshot()


          Under "trying different modifications" I mean either creating component with different initial props or interacting with component's internal elements' props.



          test('closes list on button clicked', () => {
          let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
          wrapper.find('button').at(0).simulate('click');
          expect(wrapper).toMatchSnapshot();
          });


          This way you never need to test methods separately. Why do I believe this make sense?



          While having all per-method tests passed we still cannot say if it works as a whole(false-positive reaction).
          Also if we do any refactoring like renaming method our tests-per-method will fail. At the same time component may still work perfectly fine and we spend more time to fix tests just to have them pass(false-negative reaction).



          From the opposite focusing on render() outcomes(that's what Enzyme adapter does under the hood of .toMatchSnapshot() matcher) we test what our element does as a part of React project.



          [UPD] Example based on your code:



          describe("<FetchData />", () => {
          let wrapper;
          global.fetch = jest.fn();

          beforeEach(() => {
          fetch.mockClear();
          });

          function makeFetchReturning(documents) {
          fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
          }

          function initComponent() {
          // if we run this in beforeEach we would not able to mock different return value for fetch() mock
          wrapper = shallow(<FetchData />);
          }

          test("calls appropriate API endpoint", () => {
          makeFetchReturning();
          initComponent();
          expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
          });

          test("displays loading placeholder until data is fetched", () => {
          // promise that is never resolved
          fetch.mockImplementation(() => new Promise(() => {}));
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("looks well when empty data returned", () => {
          makeFetchReturning();
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("reloads documents and displays them", () => {
          makeFetchReturning();
          initComponent();
          // no matter what values we include in mock but it should be something non-empty
          makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
          wrapper.find('button').at(0).simulate('click');
          expect(fetch).toHaveBeenCalledTimes(2);
          expect(wrapper).toMatchSnapshot();
          })

          });





          share|improve this answer























          • I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
            – Alex Harvey
            Nov 20 '18 at 10:20












          • Could you please give an example using the class I attached to my original question? :)
            – Alex Harvey
            Nov 20 '18 at 10:21






          • 1




            updated with example
            – skyboyer
            Nov 20 '18 at 10:51










          • Amazing. Thank you very much!
            – Alex Harvey
            Nov 20 '18 at 10:54










          • Note: I also needed to add enzyme and set that up for shallow :)
            – Alex Harvey
            Nov 20 '18 at 13:16











          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%2f53376966%2fjest-how-to-test-output-of-react-methods-is-correct%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














          I follow next approach:





          1. Mocking dependencies called explicitly by component under test.

          2. Initializing component with shallow()

          3. trying different modifications

          4. Checking component with .toMatchSnapshot()


          Under "trying different modifications" I mean either creating component with different initial props or interacting with component's internal elements' props.



          test('closes list on button clicked', () => {
          let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
          wrapper.find('button').at(0).simulate('click');
          expect(wrapper).toMatchSnapshot();
          });


          This way you never need to test methods separately. Why do I believe this make sense?



          While having all per-method tests passed we still cannot say if it works as a whole(false-positive reaction).
          Also if we do any refactoring like renaming method our tests-per-method will fail. At the same time component may still work perfectly fine and we spend more time to fix tests just to have them pass(false-negative reaction).



          From the opposite focusing on render() outcomes(that's what Enzyme adapter does under the hood of .toMatchSnapshot() matcher) we test what our element does as a part of React project.



          [UPD] Example based on your code:



          describe("<FetchData />", () => {
          let wrapper;
          global.fetch = jest.fn();

          beforeEach(() => {
          fetch.mockClear();
          });

          function makeFetchReturning(documents) {
          fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
          }

          function initComponent() {
          // if we run this in beforeEach we would not able to mock different return value for fetch() mock
          wrapper = shallow(<FetchData />);
          }

          test("calls appropriate API endpoint", () => {
          makeFetchReturning();
          initComponent();
          expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
          });

          test("displays loading placeholder until data is fetched", () => {
          // promise that is never resolved
          fetch.mockImplementation(() => new Promise(() => {}));
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("looks well when empty data returned", () => {
          makeFetchReturning();
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("reloads documents and displays them", () => {
          makeFetchReturning();
          initComponent();
          // no matter what values we include in mock but it should be something non-empty
          makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
          wrapper.find('button').at(0).simulate('click');
          expect(fetch).toHaveBeenCalledTimes(2);
          expect(wrapper).toMatchSnapshot();
          })

          });





          share|improve this answer























          • I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
            – Alex Harvey
            Nov 20 '18 at 10:20












          • Could you please give an example using the class I attached to my original question? :)
            – Alex Harvey
            Nov 20 '18 at 10:21






          • 1




            updated with example
            – skyboyer
            Nov 20 '18 at 10:51










          • Amazing. Thank you very much!
            – Alex Harvey
            Nov 20 '18 at 10:54










          • Note: I also needed to add enzyme and set that up for shallow :)
            – Alex Harvey
            Nov 20 '18 at 13:16
















          2














          I follow next approach:





          1. Mocking dependencies called explicitly by component under test.

          2. Initializing component with shallow()

          3. trying different modifications

          4. Checking component with .toMatchSnapshot()


          Under "trying different modifications" I mean either creating component with different initial props or interacting with component's internal elements' props.



          test('closes list on button clicked', () => {
          let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
          wrapper.find('button').at(0).simulate('click');
          expect(wrapper).toMatchSnapshot();
          });


          This way you never need to test methods separately. Why do I believe this make sense?



          While having all per-method tests passed we still cannot say if it works as a whole(false-positive reaction).
          Also if we do any refactoring like renaming method our tests-per-method will fail. At the same time component may still work perfectly fine and we spend more time to fix tests just to have them pass(false-negative reaction).



          From the opposite focusing on render() outcomes(that's what Enzyme adapter does under the hood of .toMatchSnapshot() matcher) we test what our element does as a part of React project.



          [UPD] Example based on your code:



          describe("<FetchData />", () => {
          let wrapper;
          global.fetch = jest.fn();

          beforeEach(() => {
          fetch.mockClear();
          });

          function makeFetchReturning(documents) {
          fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
          }

          function initComponent() {
          // if we run this in beforeEach we would not able to mock different return value for fetch() mock
          wrapper = shallow(<FetchData />);
          }

          test("calls appropriate API endpoint", () => {
          makeFetchReturning();
          initComponent();
          expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
          });

          test("displays loading placeholder until data is fetched", () => {
          // promise that is never resolved
          fetch.mockImplementation(() => new Promise(() => {}));
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("looks well when empty data returned", () => {
          makeFetchReturning();
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("reloads documents and displays them", () => {
          makeFetchReturning();
          initComponent();
          // no matter what values we include in mock but it should be something non-empty
          makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
          wrapper.find('button').at(0).simulate('click');
          expect(fetch).toHaveBeenCalledTimes(2);
          expect(wrapper).toMatchSnapshot();
          })

          });





          share|improve this answer























          • I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
            – Alex Harvey
            Nov 20 '18 at 10:20












          • Could you please give an example using the class I attached to my original question? :)
            – Alex Harvey
            Nov 20 '18 at 10:21






          • 1




            updated with example
            – skyboyer
            Nov 20 '18 at 10:51










          • Amazing. Thank you very much!
            – Alex Harvey
            Nov 20 '18 at 10:54










          • Note: I also needed to add enzyme and set that up for shallow :)
            – Alex Harvey
            Nov 20 '18 at 13:16














          2












          2








          2






          I follow next approach:





          1. Mocking dependencies called explicitly by component under test.

          2. Initializing component with shallow()

          3. trying different modifications

          4. Checking component with .toMatchSnapshot()


          Under "trying different modifications" I mean either creating component with different initial props or interacting with component's internal elements' props.



          test('closes list on button clicked', () => {
          let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
          wrapper.find('button').at(0).simulate('click');
          expect(wrapper).toMatchSnapshot();
          });


          This way you never need to test methods separately. Why do I believe this make sense?



          While having all per-method tests passed we still cannot say if it works as a whole(false-positive reaction).
          Also if we do any refactoring like renaming method our tests-per-method will fail. At the same time component may still work perfectly fine and we spend more time to fix tests just to have them pass(false-negative reaction).



          From the opposite focusing on render() outcomes(that's what Enzyme adapter does under the hood of .toMatchSnapshot() matcher) we test what our element does as a part of React project.



          [UPD] Example based on your code:



          describe("<FetchData />", () => {
          let wrapper;
          global.fetch = jest.fn();

          beforeEach(() => {
          fetch.mockClear();
          });

          function makeFetchReturning(documents) {
          fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
          }

          function initComponent() {
          // if we run this in beforeEach we would not able to mock different return value for fetch() mock
          wrapper = shallow(<FetchData />);
          }

          test("calls appropriate API endpoint", () => {
          makeFetchReturning();
          initComponent();
          expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
          });

          test("displays loading placeholder until data is fetched", () => {
          // promise that is never resolved
          fetch.mockImplementation(() => new Promise(() => {}));
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("looks well when empty data returned", () => {
          makeFetchReturning();
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("reloads documents and displays them", () => {
          makeFetchReturning();
          initComponent();
          // no matter what values we include in mock but it should be something non-empty
          makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
          wrapper.find('button').at(0).simulate('click');
          expect(fetch).toHaveBeenCalledTimes(2);
          expect(wrapper).toMatchSnapshot();
          })

          });





          share|improve this answer














          I follow next approach:





          1. Mocking dependencies called explicitly by component under test.

          2. Initializing component with shallow()

          3. trying different modifications

          4. Checking component with .toMatchSnapshot()


          Under "trying different modifications" I mean either creating component with different initial props or interacting with component's internal elements' props.



          test('closes list on button clicked', () => {
          let wrapper = shallow(<MyComponent prop1={'a'} prop2={'b'} />);
          wrapper.find('button').at(0).simulate('click');
          expect(wrapper).toMatchSnapshot();
          });


          This way you never need to test methods separately. Why do I believe this make sense?



          While having all per-method tests passed we still cannot say if it works as a whole(false-positive reaction).
          Also if we do any refactoring like renaming method our tests-per-method will fail. At the same time component may still work perfectly fine and we spend more time to fix tests just to have them pass(false-negative reaction).



          From the opposite focusing on render() outcomes(that's what Enzyme adapter does under the hood of .toMatchSnapshot() matcher) we test what our element does as a part of React project.



          [UPD] Example based on your code:



          describe("<FetchData />", () => {
          let wrapper;
          global.fetch = jest.fn();

          beforeEach(() => {
          fetch.mockClear();
          });

          function makeFetchReturning(documents) {
          fetch.mockImplementation(() => Promise.resolve({ json: () => documents }));
          }

          function initComponent() {
          // if we run this in beforeEach we would not able to mock different return value for fetch() mock
          wrapper = shallow(<FetchData />);
          }

          test("calls appropriate API endpoint", () => {
          makeFetchReturning();
          initComponent();
          expect(fetch).toHaveBeenCalledWith("api/SampleData/GetDocuments");
          });

          test("displays loading placeholder until data is fetched", () => {
          // promise that is never resolved
          fetch.mockImplementation(() => new Promise(() => {}));
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("looks well when empty data returned", () => {
          makeFetchReturning();
          initComponent();
          expect(wrapper).toMatchSnapshot();
          });

          test("reloads documents and displays them", () => {
          makeFetchReturning();
          initComponent();
          // no matter what values we include in mock but it should be something non-empty
          makeFetchReturning([{fileName: '_', currentSite: '1', correctSite: '2'}]);
          wrapper.find('button').at(0).simulate('click');
          expect(fetch).toHaveBeenCalledTimes(2);
          expect(wrapper).toMatchSnapshot();
          })

          });






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 10:51

























          answered Nov 19 '18 at 15:02









          skyboyer

          3,33611128




          3,33611128












          • I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
            – Alex Harvey
            Nov 20 '18 at 10:20












          • Could you please give an example using the class I attached to my original question? :)
            – Alex Harvey
            Nov 20 '18 at 10:21






          • 1




            updated with example
            – skyboyer
            Nov 20 '18 at 10:51










          • Amazing. Thank you very much!
            – Alex Harvey
            Nov 20 '18 at 10:54










          • Note: I also needed to add enzyme and set that up for shallow :)
            – Alex Harvey
            Nov 20 '18 at 13:16


















          • I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
            – Alex Harvey
            Nov 20 '18 at 10:20












          • Could you please give an example using the class I attached to my original question? :)
            – Alex Harvey
            Nov 20 '18 at 10:21






          • 1




            updated with example
            – skyboyer
            Nov 20 '18 at 10:51










          • Amazing. Thank you very much!
            – Alex Harvey
            Nov 20 '18 at 10:54










          • Note: I also needed to add enzyme and set that up for shallow :)
            – Alex Harvey
            Nov 20 '18 at 13:16
















          I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
          – Alex Harvey
          Nov 20 '18 at 10:20






          I am trying lots of the stuff like you said however am still not getting it right. None of the tutorials online seem to have example that look like my react class. E.g import React from 'react'; import FetchData from './fetchdata'; import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer .create(<FetchData></FetchData>) .toJSON(); expect(tree).toMatchSnapshot(); }); Just doesn't work.
          – Alex Harvey
          Nov 20 '18 at 10:20














          Could you please give an example using the class I attached to my original question? :)
          – Alex Harvey
          Nov 20 '18 at 10:21




          Could you please give an example using the class I attached to my original question? :)
          – Alex Harvey
          Nov 20 '18 at 10:21




          1




          1




          updated with example
          – skyboyer
          Nov 20 '18 at 10:51




          updated with example
          – skyboyer
          Nov 20 '18 at 10:51












          Amazing. Thank you very much!
          – Alex Harvey
          Nov 20 '18 at 10:54




          Amazing. Thank you very much!
          – Alex Harvey
          Nov 20 '18 at 10:54












          Note: I also needed to add enzyme and set that up for shallow :)
          – Alex Harvey
          Nov 20 '18 at 13:16




          Note: I also needed to add enzyme and set that up for shallow :)
          – Alex Harvey
          Nov 20 '18 at 13:16


















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f53376966%2fjest-how-to-test-output-of-react-methods-is-correct%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

          MongoDB - Not Authorized To Execute Command

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

          Npm cannot find a required file even through it is in the searched directory