How to mock/test event listeners with mocha/jest?How to find event listeners on a DOM node when debugging or from the JavaScript code?How do I test for an empty JavaScript object?How to run a single test with Mocha?How to increase timeout for a single test case in mochaHow do you manually mock one of your own files in Jest?How does variable scope work within the Mocha test framework?How do I run a single test using Jest?How to “mock” navigator.geolocation in a React Jest TestJest: Trying to mock nested functions and redirects in jest, but no availHow to handle UnhandledPromiseRejectionWarning in simple Mocha Unit Tests

Numbers Decrease while Letters Increase

Can a Rogue PC teach an NPC to perform Sneak Attack?

What is the best type of paint to paint a shipping container?

Heyacrazy: No Diagonals

Why did Khan ask Admiral James T. Kirk about Project Genesis?

Tex Quotes(UVa 272)

How do I make my image comply with the requirements of this photography competition?

Handling Disruptive Student on the Autistic Spectrum

Did anyone try to find the little box that held Professor Moriarty and his wife after the crash?

Where can/should I, as a high schooler, publish a paper regarding the derivation of a formula?

Sum ergo cogito?

How would a Creature that needs to be seen by Humans evolve?

What should come first—characters or plot?

Is there any way white can win?

What does zitch dog mean?

The No-Free-Lunch Theorem and K-NN consistency

Papers on arXiv solving the same problem at the same time

Did a flight controller ever answer Flight with a no-go?

“T” in subscript in formulas

Network helper class with retry logic on failure

How to find out the average duration of the peer-review process for a given journal?

How do we calculate energy of food?

Showing that the limit of non-eigenvector goes to infinity

Nothing like a good ol' game of ModTen



How to mock/test event listeners with mocha/jest?


How to find event listeners on a DOM node when debugging or from the JavaScript code?How do I test for an empty JavaScript object?How to run a single test with Mocha?How to increase timeout for a single test case in mochaHow do you manually mock one of your own files in Jest?How does variable scope work within the Mocha test framework?How do I run a single test using Jest?How to “mock” navigator.geolocation in a React Jest TestJest: Trying to mock nested functions and redirects in jest, but no availHow to handle UnhandledPromiseRejectionWarning in simple Mocha Unit Tests






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















class Router 
constructor()
window.onhashchange = this.hashChange;


hashChange()
console.log('Hash Changed');
return true;



export default Router;


I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed










share|improve this question
































    2















    class Router 
    constructor()
    window.onhashchange = this.hashChange;


    hashChange()
    console.log('Hash Changed');
    return true;



    export default Router;


    I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed










    share|improve this question




























      2












      2








      2








      class Router 
      constructor()
      window.onhashchange = this.hashChange;


      hashChange()
      console.log('Hash Changed');
      return true;



      export default Router;


      I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed










      share|improve this question
















      class Router 
      constructor()
      window.onhashchange = this.hashChange;


      hashChange()
      console.log('Hash Changed');
      return true;



      export default Router;


      I am trying to find a way to test the above piece of code in node.js. But there is no window object in node. How to mock objects and test event listeners using mocha/jest? The goal is to test that hashChange() is invoked when URL hash is changed







      javascript testing mocha jestjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 5 at 8:10









      skyboyer

      6,1871 gold badge17 silver badges37 bronze badges




      6,1871 gold badge17 silver badges37 bronze badges










      asked Mar 27 at 18:30









      lchlch

      9682 gold badges24 silver badges52 bronze badges




      9682 gold badges24 silver badges52 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          2















          The default test environment in Jest is a browser-like environment provided by jsdom.



          jsdom provides window so it is available by default for tests running in Jest.



          You can use Jest to test the above code like this:



          class Router 
          constructor()
          window.onhashchange = this.hashChange;


          hashChange()
          console.log('Hash Changed');
          return true;



          test('Router', () =>
          const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
          const router = new Router();
          window.onhashchange();
          expect(hashChangeSpy).toHaveBeenCalled(); // Success!
          );





          share|improve this answer

























          • The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

            – lch
            Mar 27 at 19:54











          • @lch it’s included with jest and is used automatically with the default configuration settings

            – brian-lives-outdoors
            Mar 27 at 20:11










          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%2f55384258%2fhow-to-mock-test-event-listeners-with-mocha-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









          2















          The default test environment in Jest is a browser-like environment provided by jsdom.



          jsdom provides window so it is available by default for tests running in Jest.



          You can use Jest to test the above code like this:



          class Router 
          constructor()
          window.onhashchange = this.hashChange;


          hashChange()
          console.log('Hash Changed');
          return true;



          test('Router', () =>
          const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
          const router = new Router();
          window.onhashchange();
          expect(hashChangeSpy).toHaveBeenCalled(); // Success!
          );





          share|improve this answer

























          • The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

            – lch
            Mar 27 at 19:54











          • @lch it’s included with jest and is used automatically with the default configuration settings

            – brian-lives-outdoors
            Mar 27 at 20:11















          2















          The default test environment in Jest is a browser-like environment provided by jsdom.



          jsdom provides window so it is available by default for tests running in Jest.



          You can use Jest to test the above code like this:



          class Router 
          constructor()
          window.onhashchange = this.hashChange;


          hashChange()
          console.log('Hash Changed');
          return true;



          test('Router', () =>
          const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
          const router = new Router();
          window.onhashchange();
          expect(hashChangeSpy).toHaveBeenCalled(); // Success!
          );





          share|improve this answer

























          • The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

            – lch
            Mar 27 at 19:54











          • @lch it’s included with jest and is used automatically with the default configuration settings

            – brian-lives-outdoors
            Mar 27 at 20:11













          2














          2










          2









          The default test environment in Jest is a browser-like environment provided by jsdom.



          jsdom provides window so it is available by default for tests running in Jest.



          You can use Jest to test the above code like this:



          class Router 
          constructor()
          window.onhashchange = this.hashChange;


          hashChange()
          console.log('Hash Changed');
          return true;



          test('Router', () =>
          const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
          const router = new Router();
          window.onhashchange();
          expect(hashChangeSpy).toHaveBeenCalled(); // Success!
          );





          share|improve this answer













          The default test environment in Jest is a browser-like environment provided by jsdom.



          jsdom provides window so it is available by default for tests running in Jest.



          You can use Jest to test the above code like this:



          class Router 
          constructor()
          window.onhashchange = this.hashChange;


          hashChange()
          console.log('Hash Changed');
          return true;



          test('Router', () =>
          const hashChangeSpy = jest.spyOn(Router.prototype, 'hashChange');
          const router = new Router();
          window.onhashchange();
          expect(hashChangeSpy).toHaveBeenCalled(); // Success!
          );






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 27 at 19:07









          brian-lives-outdoorsbrian-lives-outdoors

          15.4k1 gold badge18 silver badges45 bronze badges




          15.4k1 gold badge18 silver badges45 bronze badges















          • The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

            – lch
            Mar 27 at 19:54











          • @lch it’s included with jest and is used automatically with the default configuration settings

            – brian-lives-outdoors
            Mar 27 at 20:11

















          • The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

            – lch
            Mar 27 at 19:54











          • @lch it’s included with jest and is used automatically with the default configuration settings

            – brian-lives-outdoors
            Mar 27 at 20:11
















          The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

          – lch
          Mar 27 at 19:54





          The default test environment in Jest is a browser-like environment provided by jsdom So, do i need to add jsdom to my package.json? or does it come with jest?

          – lch
          Mar 27 at 19:54













          @lch it’s included with jest and is used automatically with the default configuration settings

          – brian-lives-outdoors
          Mar 27 at 20:11





          @lch it’s included with jest and is used automatically with the default configuration settings

          – brian-lives-outdoors
          Mar 27 at 20:11








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          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%2f55384258%2fhow-to-mock-test-event-listeners-with-mocha-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







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript