Вы не можете использовать .simulate
метод enzyme
, чтобы вызвать событие DOM.Этот метод используется для запуска React SyntheticEvent
, а не собственного события DOM.И вам не нужно проверять реальные события wheel
и load
для реального DOM.Это обязанность теста e2e, а не обязанность юнит-теста.
Вот решение для юнит-теста:
index.tsx
:
import React, { Component } from 'react';
class XComponent extends Component {
private domElement;
constructor(props) {
super(props);
this.load = this.load.bind(this);
}
public componentDidMount() {
this.domElement = document.getElementById('myImg');
if (this.domElement) {
this.domElement.addEventListener('load', this.load);
}
}
public load() {
this.domElement.addEventListener('wheel', this.onWheel);
}
public onWheel() {
//
}
public render() {
return <div>XComponent</div>;
}
}
export default XComponent;
index.spec.tsx
:
import React from 'react';
import XComponent from './';
import { shallow } from 'enzyme';
let map = {};
document.addEventListener = jest.fn((event, cb) => {
map[event] = cb;
});
describe('XComponent', () => {
let domElementEventMap = {};
const mockedDomElement: any = {
addEventListener: jest.fn((event, cb) => {
domElementEventMap[event] = cb;
})
};
afterEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
map = {};
domElementEventMap = {};
});
it('should call onWheel method', () => {
const getElementByIdSpy = jest.spyOn(document, 'getElementById').mockReturnValueOnce(mockedDomElement);
const wrapper = shallow(<XComponent></XComponent>);
expect(wrapper.text()).toBe('XComponent');
expect(getElementByIdSpy).toBeCalledWith('myImg');
expect(mockedDomElement.addEventListener).toBeCalledWith('load', (wrapper.instance() as any).load);
(domElementEventMap as any).load();
expect(mockedDomElement.addEventListener).toBeCalledWith('wheel', (wrapper.instance() as any).onWheel);
});
it('should not add load event when dom element does not exist', () => {
const getElementByIdSpy = jest.spyOn(document, 'getElementById').mockReturnValueOnce(null);
const wrapper = shallow(<XComponent></XComponent>);
expect(wrapper.text()).toBe('XComponent');
expect(getElementByIdSpy).toBeCalledWith('myImg');
expect(mockedDomElement.addEventListener).not.toBeCalled();
});
});
Результат модульного теста с отчетом о покрытии 100%:
PASS src/stackoverflow/58028571/index.spec.tsx (13.467s)
XComponent
✓ should call onWheel method (10ms)
✓ should not add load event when dom element does not exist (2ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 83.33 | 100 | |
index.tsx | 100 | 100 | 83.33 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 15.545s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58028571