Mocking a React Component using Jest












1















I'm trying to mock one of my components across all tests. The reason is that it is using a copy of an older version of D3 in a local package, and this D3 has references to "this.document", which errors out when running Jest tests. This is probably due to the reasons described here: https://github.com/facebook/jest/issues/3970



package.json



  "devDependencies": {
"enzyme": "^3.7.0",
"enzyme-adapter-react-16": "^1.7.0",
"eslint": "5.6.0",
"eslint-config-airbnb-base": "13.1.0",
"react-scripts": "^2.0.4",
"react-test-renderer": "^16.6.3",
"redux-devtools": "^3.4.1",
"redux-devtools-dock-monitor": "^1.1.3",
"redux-devtools-log-monitor": "^1.4.0",
"redux-logger": "^3.0.6"
...
"scripts": {
"test": "react-scripts test --env=jsdom --passWithNoTests"


src/setupTests.js



import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

import jest from 'jest';
import BarChart from './components/d3/BarChart/BarChart';

jest.mock('BarChart');

BarChart.render.mockResolvedValue(null);


However, when I run npm test, I still get:



TypeError: Cannot read property 'document' of undefined

6 | return d3_arraySlice.call(list);
7 | };
> 8 | var d3_document = this.document;


coming from the local D3 package.



My test file:



import React from 'react';
import { shallow, mount } from 'enzyme';
import App from '../App';

it('renders without crashing - deep', () => {
mount(<App />);
});


App has a component which uses BarChart.










share|improve this question





























    1















    I'm trying to mock one of my components across all tests. The reason is that it is using a copy of an older version of D3 in a local package, and this D3 has references to "this.document", which errors out when running Jest tests. This is probably due to the reasons described here: https://github.com/facebook/jest/issues/3970



    package.json



      "devDependencies": {
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0",
    "eslint": "5.6.0",
    "eslint-config-airbnb-base": "13.1.0",
    "react-scripts": "^2.0.4",
    "react-test-renderer": "^16.6.3",
    "redux-devtools": "^3.4.1",
    "redux-devtools-dock-monitor": "^1.1.3",
    "redux-devtools-log-monitor": "^1.4.0",
    "redux-logger": "^3.0.6"
    ...
    "scripts": {
    "test": "react-scripts test --env=jsdom --passWithNoTests"


    src/setupTests.js



    import { configure } from 'enzyme';
    import Adapter from 'enzyme-adapter-react-16';
    configure({ adapter: new Adapter() });

    import jest from 'jest';
    import BarChart from './components/d3/BarChart/BarChart';

    jest.mock('BarChart');

    BarChart.render.mockResolvedValue(null);


    However, when I run npm test, I still get:



    TypeError: Cannot read property 'document' of undefined

    6 | return d3_arraySlice.call(list);
    7 | };
    > 8 | var d3_document = this.document;


    coming from the local D3 package.



    My test file:



    import React from 'react';
    import { shallow, mount } from 'enzyme';
    import App from '../App';

    it('renders without crashing - deep', () => {
    mount(<App />);
    });


    App has a component which uses BarChart.










    share|improve this question



























      1












      1








      1


      0






      I'm trying to mock one of my components across all tests. The reason is that it is using a copy of an older version of D3 in a local package, and this D3 has references to "this.document", which errors out when running Jest tests. This is probably due to the reasons described here: https://github.com/facebook/jest/issues/3970



      package.json



        "devDependencies": {
      "enzyme": "^3.7.0",
      "enzyme-adapter-react-16": "^1.7.0",
      "eslint": "5.6.0",
      "eslint-config-airbnb-base": "13.1.0",
      "react-scripts": "^2.0.4",
      "react-test-renderer": "^16.6.3",
      "redux-devtools": "^3.4.1",
      "redux-devtools-dock-monitor": "^1.1.3",
      "redux-devtools-log-monitor": "^1.4.0",
      "redux-logger": "^3.0.6"
      ...
      "scripts": {
      "test": "react-scripts test --env=jsdom --passWithNoTests"


      src/setupTests.js



      import { configure } from 'enzyme';
      import Adapter from 'enzyme-adapter-react-16';
      configure({ adapter: new Adapter() });

      import jest from 'jest';
      import BarChart from './components/d3/BarChart/BarChart';

      jest.mock('BarChart');

      BarChart.render.mockResolvedValue(null);


      However, when I run npm test, I still get:



      TypeError: Cannot read property 'document' of undefined

      6 | return d3_arraySlice.call(list);
      7 | };
      > 8 | var d3_document = this.document;


      coming from the local D3 package.



      My test file:



      import React from 'react';
      import { shallow, mount } from 'enzyme';
      import App from '../App';

      it('renders without crashing - deep', () => {
      mount(<App />);
      });


      App has a component which uses BarChart.










      share|improve this question
















      I'm trying to mock one of my components across all tests. The reason is that it is using a copy of an older version of D3 in a local package, and this D3 has references to "this.document", which errors out when running Jest tests. This is probably due to the reasons described here: https://github.com/facebook/jest/issues/3970



      package.json



        "devDependencies": {
      "enzyme": "^3.7.0",
      "enzyme-adapter-react-16": "^1.7.0",
      "eslint": "5.6.0",
      "eslint-config-airbnb-base": "13.1.0",
      "react-scripts": "^2.0.4",
      "react-test-renderer": "^16.6.3",
      "redux-devtools": "^3.4.1",
      "redux-devtools-dock-monitor": "^1.1.3",
      "redux-devtools-log-monitor": "^1.4.0",
      "redux-logger": "^3.0.6"
      ...
      "scripts": {
      "test": "react-scripts test --env=jsdom --passWithNoTests"


      src/setupTests.js



      import { configure } from 'enzyme';
      import Adapter from 'enzyme-adapter-react-16';
      configure({ adapter: new Adapter() });

      import jest from 'jest';
      import BarChart from './components/d3/BarChart/BarChart';

      jest.mock('BarChart');

      BarChart.render.mockResolvedValue(null);


      However, when I run npm test, I still get:



      TypeError: Cannot read property 'document' of undefined

      6 | return d3_arraySlice.call(list);
      7 | };
      > 8 | var d3_document = this.document;


      coming from the local D3 package.



      My test file:



      import React from 'react';
      import { shallow, mount } from 'enzyme';
      import App from '../App';

      it('renders without crashing - deep', () => {
      mount(<App />);
      });


      App has a component which uses BarChart.







      reactjs jestjs enzyme






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 10:24









      skyboyer

      4,08311230




      4,08311230










      asked Nov 22 '18 at 2:00









      user994165user994165

      3,7101864113




      3,7101864113
























          1 Answer
          1






          active

          oldest

          votes


















          1
















          Issue



          import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.





          Solution



          The component does not need to be imported in order to mock it.



          Either provide a module factory function as the second parameter to jest.mock:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);


          or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart and simply call jest.mock with the path to the component:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart');





          share|improve this answer
























          • when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

            – user994165
            Nov 26 '18 at 21:13











          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%2f53422889%2fmocking-a-react-component-using-jest%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









          1
















          Issue



          import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.





          Solution



          The component does not need to be imported in order to mock it.



          Either provide a module factory function as the second parameter to jest.mock:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);


          or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart and simply call jest.mock with the path to the component:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart');





          share|improve this answer
























          • when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

            – user994165
            Nov 26 '18 at 21:13
















          1
















          Issue



          import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.





          Solution



          The component does not need to be imported in order to mock it.



          Either provide a module factory function as the second parameter to jest.mock:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);


          or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart and simply call jest.mock with the path to the component:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart');





          share|improve this answer
























          • when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

            – user994165
            Nov 26 '18 at 21:13














          1












          1








          1









          Issue



          import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.





          Solution



          The component does not need to be imported in order to mock it.



          Either provide a module factory function as the second parameter to jest.mock:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);


          or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart and simply call jest.mock with the path to the component:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart');





          share|improve this answer















          Issue



          import BarChart from './components/d3/BarChart/BarChart'; ends up running code that includes a reference to this.document which causes the error.





          Solution



          The component does not need to be imported in order to mock it.



          Either provide a module factory function as the second parameter to jest.mock:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart', /* provide your module factory function here */);


          or create a mock for the component at ./components/d3/BarChart/__mocks__/BarChart and simply call jest.mock with the path to the component:



          import { configure } from 'enzyme';
          import Adapter from 'enzyme-adapter-react-16';
          configure({ adapter: new Adapter() });

          jest.mock('./components/d3/BarChart/BarChart');






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 '18 at 4:03









          brian-lives-outdoorsbrian-lives-outdoors

          8,3421725




          8,3421725













          • when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

            – user994165
            Nov 26 '18 at 21:13



















          • when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

            – user994165
            Nov 26 '18 at 21:13

















          when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

          – user994165
          Nov 26 '18 at 21:13





          when I used the mocks folder option, it wouldn't find the new module. I read somewhere about there being problems with nested modules. For the first option, that's also not working for me. I opened a new question: stackoverflow.com/questions/53488371/jest-not-using-manual-mock

          – user994165
          Nov 26 '18 at 21:13




















          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%2f53422889%2fmocking-a-react-component-using-jest%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







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini