My React组件必须响应调整大小事件,我正在使用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)
似乎没有返回任何内容。
我的印象是Jest会检查所需的模块(jQuery)的API来构建它的模拟,但是如果我正确地理解了这个问题,那么似乎没有发生这种情况?
我可以通过不嘲笑jQuery来解决这个问题,但显然这并不是完全可取的。
答案 0 :(得分:0)
这是使用jestjs
和enzyme
的单元测试解决方案:
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