I have some unit tests set up, testing with enzyme's shallow method with a jsdom configuration. This has been working well until I have run into a component where I am using window.addEventListener
. The unit tests is now giving back the error of
TypeError: window.addEventListener is not a function
I have my test helpers set up for JSdom like so
import jsdom from 'jsdom';
...
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};
this was working fine, then I upgraded to enzyme 3.x, and now I am getting this error.
I am wondering do i need to manually mock the addEventListener now, or is there something I am doing wrong to access this.
//in test file ...
it("should render KeyStrokeHandler", () => {
// Set-up event listener mock
const map = {};
window.addEventListener = jest.fn((event, callback) => {
map[event] = callback;
});
// Mount component that has set callback for keydown event
const wrapper = mount(<KeyStrokeHandler />);
// Trigger keydown event
map.keydown({ key: 'Enter' });
});
...
I had the same issue in trying to check if the addEventListener has been called in componentDidMount this seems to work for me (jest, enzyme)
//component
componentDidMount(){
document.addEventListener("keydown", this.handleKeydownOnSearch, false);
}
....
//in test file ...
it("on component mount we set the keydown listener", () => {
global.document.addEventListener = jest.fn();
wrapper = shallow(<ItemSearch />);
expect(global.document.addEventListener).toHaveBeenCalled();
});
...
I mock my document
just like you do, and then if I need to use addEventListener()
in a test, I just mock it in a beforeEach
beforeEach(() => {
document = {
...document,
addEventListener: () => { },
removeEventListener: () => { }
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With