Jest with fetch-mock generating error: TypeError: Cannot read property 'prototype' of undefined when using on...












2















I'm almost sure it's my mistake, but I spent one entire day trying to solve and I've being failed 😞.



I'm trying to configure the fetch-mock on node to use with jest. I tried a lot of things and the best result that I have is this:



https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png



I'm sure my mock is working because if I pass it through parameter to the "Myclass.query" it works perfectly.



I'm also sure that the mock is arriving in my test file, because the mock function is present in the fetch module.



But... all together aren't working 😭.



I created a very simple and small project to see this problem happening:



https://github.com/cesarjr/test-node-fetch



Can anyone help me?










share|improve this question



























    2















    I'm almost sure it's my mistake, but I spent one entire day trying to solve and I've being failed 😞.



    I'm trying to configure the fetch-mock on node to use with jest. I tried a lot of things and the best result that I have is this:



    https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png



    I'm sure my mock is working because if I pass it through parameter to the "Myclass.query" it works perfectly.



    I'm also sure that the mock is arriving in my test file, because the mock function is present in the fetch module.



    But... all together aren't working 😭.



    I created a very simple and small project to see this problem happening:



    https://github.com/cesarjr/test-node-fetch



    Can anyone help me?










    share|improve this question

























      2












      2








      2








      I'm almost sure it's my mistake, but I spent one entire day trying to solve and I've being failed 😞.



      I'm trying to configure the fetch-mock on node to use with jest. I tried a lot of things and the best result that I have is this:



      https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png



      I'm sure my mock is working because if I pass it through parameter to the "Myclass.query" it works perfectly.



      I'm also sure that the mock is arriving in my test file, because the mock function is present in the fetch module.



      But... all together aren't working 😭.



      I created a very simple and small project to see this problem happening:



      https://github.com/cesarjr/test-node-fetch



      Can anyone help me?










      share|improve this question














      I'm almost sure it's my mistake, but I spent one entire day trying to solve and I've being failed 😞.



      I'm trying to configure the fetch-mock on node to use with jest. I tried a lot of things and the best result that I have is this:



      https://user-images.githubusercontent.com/824198/50566568-7b49e400-0d22-11e9-884f-89720899de3a.png



      I'm sure my mock is working because if I pass it through parameter to the "Myclass.query" it works perfectly.



      I'm also sure that the mock is arriving in my test file, because the mock function is present in the fetch module.



      But... all together aren't working 😭.



      I created a very simple and small project to see this problem happening:



      https://github.com/cesarjr/test-node-fetch



      Can anyone help me?







      node.js jestjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 0:57









      CezinhaCezinha

      111




      111
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Jest uses the mock at __mocks__/node-fetch.js any time node-fetch is required during the test.



          The problem is that the first thing fetch-mock does is require node-fetch.



          This means that Request is not defined when it is set on the config here, so calling prototype on the undefined Request causes an error here.



          Someone smarter than me might know how to force Jest to require the actual node-fetch when fetch-mock requires node-fetch in the mock for node-fetch, but from what I can see it doesn't look like it is possible.





          Looks like you will have to delete the mock at __mocks__/node-fetch.js and pass fetch to your code, something like this:



          myclass.js



          class MyClass {
          static query(fetch, sessionId, query) {
          const url = 'https://api.foobar.com';

          const body = {
          sessionId,
          query
          };

          return fetch(url, {
          method: 'post',
          body: JSON.stringify(body)
          })
          .then(res => res.json());
          }
          }

          module.exports = MyClass;


          ...then create the sandbox in your test and pass it to your code, something like this:



          myclass.test.js



          const fetch = require('fetch-mock').sandbox();
          const MyClass = require('./myclass');

          describe('MyClass', () => {
          describe('.query', () => {
          it('returns the response', () => {
          fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

          expect.assertions(1);

          return MyClass.query(fetch, '123', 'the question').then((data) => {
          expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
          });
          });
          });
          });





          share|improve this answer































            0














            I've now found a reliable way to combine fetch-mock and jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest






            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%2f54000152%2fjest-with-fetch-mock-generating-error-typeerror-cannot-read-property-prototyp%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Jest uses the mock at __mocks__/node-fetch.js any time node-fetch is required during the test.



              The problem is that the first thing fetch-mock does is require node-fetch.



              This means that Request is not defined when it is set on the config here, so calling prototype on the undefined Request causes an error here.



              Someone smarter than me might know how to force Jest to require the actual node-fetch when fetch-mock requires node-fetch in the mock for node-fetch, but from what I can see it doesn't look like it is possible.





              Looks like you will have to delete the mock at __mocks__/node-fetch.js and pass fetch to your code, something like this:



              myclass.js



              class MyClass {
              static query(fetch, sessionId, query) {
              const url = 'https://api.foobar.com';

              const body = {
              sessionId,
              query
              };

              return fetch(url, {
              method: 'post',
              body: JSON.stringify(body)
              })
              .then(res => res.json());
              }
              }

              module.exports = MyClass;


              ...then create the sandbox in your test and pass it to your code, something like this:



              myclass.test.js



              const fetch = require('fetch-mock').sandbox();
              const MyClass = require('./myclass');

              describe('MyClass', () => {
              describe('.query', () => {
              it('returns the response', () => {
              fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

              expect.assertions(1);

              return MyClass.query(fetch, '123', 'the question').then((data) => {
              expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
              });
              });
              });
              });





              share|improve this answer




























                0














                Jest uses the mock at __mocks__/node-fetch.js any time node-fetch is required during the test.



                The problem is that the first thing fetch-mock does is require node-fetch.



                This means that Request is not defined when it is set on the config here, so calling prototype on the undefined Request causes an error here.



                Someone smarter than me might know how to force Jest to require the actual node-fetch when fetch-mock requires node-fetch in the mock for node-fetch, but from what I can see it doesn't look like it is possible.





                Looks like you will have to delete the mock at __mocks__/node-fetch.js and pass fetch to your code, something like this:



                myclass.js



                class MyClass {
                static query(fetch, sessionId, query) {
                const url = 'https://api.foobar.com';

                const body = {
                sessionId,
                query
                };

                return fetch(url, {
                method: 'post',
                body: JSON.stringify(body)
                })
                .then(res => res.json());
                }
                }

                module.exports = MyClass;


                ...then create the sandbox in your test and pass it to your code, something like this:



                myclass.test.js



                const fetch = require('fetch-mock').sandbox();
                const MyClass = require('./myclass');

                describe('MyClass', () => {
                describe('.query', () => {
                it('returns the response', () => {
                fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

                expect.assertions(1);

                return MyClass.query(fetch, '123', 'the question').then((data) => {
                expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
                });
                });
                });
                });





                share|improve this answer


























                  0












                  0








                  0







                  Jest uses the mock at __mocks__/node-fetch.js any time node-fetch is required during the test.



                  The problem is that the first thing fetch-mock does is require node-fetch.



                  This means that Request is not defined when it is set on the config here, so calling prototype on the undefined Request causes an error here.



                  Someone smarter than me might know how to force Jest to require the actual node-fetch when fetch-mock requires node-fetch in the mock for node-fetch, but from what I can see it doesn't look like it is possible.





                  Looks like you will have to delete the mock at __mocks__/node-fetch.js and pass fetch to your code, something like this:



                  myclass.js



                  class MyClass {
                  static query(fetch, sessionId, query) {
                  const url = 'https://api.foobar.com';

                  const body = {
                  sessionId,
                  query
                  };

                  return fetch(url, {
                  method: 'post',
                  body: JSON.stringify(body)
                  })
                  .then(res => res.json());
                  }
                  }

                  module.exports = MyClass;


                  ...then create the sandbox in your test and pass it to your code, something like this:



                  myclass.test.js



                  const fetch = require('fetch-mock').sandbox();
                  const MyClass = require('./myclass');

                  describe('MyClass', () => {
                  describe('.query', () => {
                  it('returns the response', () => {
                  fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

                  expect.assertions(1);

                  return MyClass.query(fetch, '123', 'the question').then((data) => {
                  expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
                  });
                  });
                  });
                  });





                  share|improve this answer













                  Jest uses the mock at __mocks__/node-fetch.js any time node-fetch is required during the test.



                  The problem is that the first thing fetch-mock does is require node-fetch.



                  This means that Request is not defined when it is set on the config here, so calling prototype on the undefined Request causes an error here.



                  Someone smarter than me might know how to force Jest to require the actual node-fetch when fetch-mock requires node-fetch in the mock for node-fetch, but from what I can see it doesn't look like it is possible.





                  Looks like you will have to delete the mock at __mocks__/node-fetch.js and pass fetch to your code, something like this:



                  myclass.js



                  class MyClass {
                  static query(fetch, sessionId, query) {
                  const url = 'https://api.foobar.com';

                  const body = {
                  sessionId,
                  query
                  };

                  return fetch(url, {
                  method: 'post',
                  body: JSON.stringify(body)
                  })
                  .then(res => res.json());
                  }
                  }

                  module.exports = MyClass;


                  ...then create the sandbox in your test and pass it to your code, something like this:



                  myclass.test.js



                  const fetch = require('fetch-mock').sandbox();
                  const MyClass = require('./myclass');

                  describe('MyClass', () => {
                  describe('.query', () => {
                  it('returns the response', () => {
                  fetch.mock('*', {'result': {'fulfillment': {'speech': 'The answer'}}});

                  expect.assertions(1);

                  return MyClass.query(fetch, '123', 'the question').then((data) => {
                  expect(data.result.fulfillment.speech).toBe('The answer'); // SUCCESS
                  });
                  });
                  });
                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 3 at 20:02









                  brian-lives-outdoorsbrian-lives-outdoors

                  8,3421725




                  8,3421725

























                      0














                      I've now found a reliable way to combine fetch-mock and jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest






                      share|improve this answer




























                        0














                        I've now found a reliable way to combine fetch-mock and jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest






                        share|improve this answer


























                          0












                          0








                          0







                          I've now found a reliable way to combine fetch-mock and jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest






                          share|improve this answer













                          I've now found a reliable way to combine fetch-mock and jest http://www.wheresrhys.co.uk/fetch-mock/#usageusage-with-jest







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 19 at 16:25









                          wheresrhyswheresrhys

                          12.7k1574147




                          12.7k1574147






























                              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%2f54000152%2fjest-with-fetch-mock-generating-error-typeerror-cannot-read-property-prototyp%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

                              android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                              SQL update select statement

                              WPF add header to Image with URL pettitions [duplicate]