简体   繁体   English

React +酶单元测试,无法访问window.addEventListener

[英]React + enzyme unit tests, can't access window.addEventListener

I have some unit tests set up, testing with enzyme's shallow method with a jsdom configuration. 我设置了一些单元测试,用酶的浅层方法和jsdom配置进行测试。 This has been working well until I have run into a component where I am using window.addEventListener . 这一直运行良好,直到我遇到一个我正在使用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 我为JSdom设置了测试助手,就像这样

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. 这工作正常,然后我升级到酶3.x,现在我收到此错误。

I am wondering do i need to manually mock the addEventListener now, or is there something I am doing wrong to access this. 我想知道我现在需要手动模拟addEventListener,还是有什么我做错了访问它。

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) 我在尝试检查是否已在componentDidMount中调用addEventListener时遇到了同样的问题,这似乎对我有用(开玩笑,酶)

//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();
    });
...
//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 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 我就像你一样模拟我的document ,然后如果我需要在测试中使用addEventListener() ,我只是在beforeEach模拟它

  beforeEach(() => {
    document = {
      ...document,
      addEventListener: () => { },
      removeEventListener: () => { }
    }
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM