reactjs - What is the best way to test Window Scroll Event Handlers with Enzyme? -


i have been working on react app new team , discussion came around writing unit tests components trigger methods on window.scroll events.

so, let's take component example.

import react, { component } 'react';  class mycomponent extends component {   componentdidmount() {     window.addeventlistener('scroll', this.props.myscrollmethod);   }    componentwillunmount() {     window.removeeventlistener('scroll', this.props.myscrollmethod);   }    render() {     return (       <div>         <h1>hello mycomponent!</h1>       </div>     )   }; };  export default mycomponent; 

as can see, taking method passed component via prop , binding window event listener, event scroll. in real world component call myscrollmethod user scrolling down page (let's assume use case here show sticky navigation bar when user has scrolled beyond point on page).

the problem is...i need find suitable way of testing this. end goal create spy method passed component via myscrollmethod prop, trigger scroll (or mock scroll in test) , assert whether scroll handler method has fired or not. here attempt @ this:

import react 'react'; import sinon 'sinon'; import expect, { createspy }  'expect'; import { shallow } 'enzyme';  import mycomponent './mycomponent';  describe('the <mycomponent /> component', () => {   let onscroll;   let mytestcomponent;    beforeeach(() => {     onscroll = createspy();     mytestcomponent = shallow(       <mycomponent         myscrollmethod={onscroll}         />     );   });    it('should call onscroll method when user scrolls', () => {     expect(onscroll).tonothavebeencalled();     window.dispatchevent(new window.uievent('scroll', { detail: 0 }));     expect(onscroll).tohavebeencalled();   }); }); 

the issue having final assertion failing because spy never called. i've referred number of other posts on site far have not found suitable solution. suggestions appreciated it's been racking brain while now!

thanks much!


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -