使用jQuery和window对象的React组件测试

7

我的React组件需要响应resize事件,我正在使用jQuery实现,如下:

//...
componentDidMount: function() {
  $(window).on("resize", function);
}
//..

然而,这会影响我的Jest测试,具体表现为:
- TypeError: Cannot read property 'on' of undefined
    at RadiumEnhancer.React.createClass.componentDidMount (bundles/Opportunities/OpportunityPartial.jsx:21:14)

当在Jest测试中运行时,似乎window已经被定义了,但是$(window)没有返回任何内容。

我原本以为Jest会检查所需模块(jQuery)的API来构建其模拟,但如果我正确理解问题,似乎并非如此?

我可以通过不模拟jQuery来解决这个问题,但显然这并不是完全可取的。


1
我不确定这是否正确,但我使用 beforeAll ( () => { window.jQuery = require( 'jquery' ); }); 取得了成功。或者在你的情况下使用 window.$ - Tim Malone
1个回答

1

这里是使用 jestjsenzyme 的单元测试解决方案:

index.tsx:

import React, { Component } from 'react';
import $ from 'jquery';

class SomeComponent extends Component {
  componentDidMount() {
    $(window).on('resize', this.resizeEventHandler);
  }

  resizeEventHandler() {
    console.log('resize event handler');
  }

  render() {
    return <div>some component</div>;
  }
}

export default SomeComponent;

index.spec.tsx:

import React from 'react';
import SomeComponent from './';
import { shallow } from 'enzyme';
import $ from 'jquery';

jest.mock('jquery', () => {
  const m$ = {
    on: jest.fn(),
  };
  return jest.fn(() => m$);
});

describe('36082197', () => {
  afterEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    const eventHandlerMap = {};
    ($().on as jest.MockedFunction<any>).mockImplementation((event, handler) => {
      eventHandlerMap[event] = handler;
    });
    const wrapper = shallow(<SomeComponent></SomeComponent>);
    const instance = wrapper.instance();
    expect(wrapper.text()).toBe('some component');
    expect($).toBeCalledWith(window);
    // tslint:disable-next-line: no-string-literal
    expect($(window).on).toBeCalledWith('resize', instance['resizeEventHandler']);
    eventHandlerMap['resize']();
    expect(logSpy).toBeCalledWith('resize event handler');
  });
});

单元测试结果,覆盖率达到100%:

 PASS  src/stackoverflow/36082197/index.spec.tsx (12.045s)
  36082197
    ✓ should pass (18ms)

  console.log node_modules/jest-mock/build/index.js:860
    resize event handler

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.267s, estimated 15s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/36082197


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接