【问题标题】:React + enzyme unit tests, can't access window.addEventListenerReact + 酶单元测试,无法访问 window.addEventListener
【发布时间】:2018-05-18 04:03:24
【问题描述】:

我设置了一些单元测试,使用酶的浅方法和 jsdom 配置进行测试。这一直运行良好,直到我遇到我正在使用window.addEventListener 的组件。单元测试现在返回

的错误
TypeError: window.addEventListener is not a function

我已经为 JSdom 设置了我的测试助手,就像这样

import jsdom from 'jsdom';

...

global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};

这工作正常,然后我升级到酶 3.x,现在我收到此错误。

我想知道我现在是否需要手动模拟 addEventListener,或者我做错了什么来访问它。

【问题讨论】:

    标签: javascript reactjs unit-testing enzyme jsdom


    【解决方案1】:
    //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' });
      });
    
    ...
    

    【讨论】:

      【解决方案2】:

      我在尝试检查是否在 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();
          });
      ...
      

      【讨论】:

        【解决方案3】:

        我像你一样模拟我的document,然后如果我需要在测试中使用addEventListener(),我只需在beforeEach 中模拟它

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

        【讨论】:

        • 2017 年 3 月之后的玩笑打破了这种嘲弄方式。但@parth-navadiya 答案仍然有效
        猜你喜欢
        • 1970-01-01
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 2021-03-14
        • 2014-12-28
        • 2017-06-16
        相关资源
        最近更新 更多