Вот завершенная демонстрация:
index.tsx
:
import React, { Component } from 'react';
class SomeComponent extends Component {
constructor(props) {
super(props);
this.handleButtonsClicks = this.handleButtonsClicks.bind(this);
}
handleButtonsClicks(e) {
if (e.target.parentNode.getAttribute('id') === 'id1') {
console.log('do something');
} else if (e.target.getAttribute('id') === 'id2') {
console.log('do another thing');
}
}
render() {
return (
<div>
<button id="id1" onClick={this.handleButtonsClicks}>
Button 1
</button>
<button id="id2" onClick={this.handleButtonsClicks}>
Button 2
</button>
</div>
);
}
}
export default SomeComponent;
index.spec.tsx
:
import React from 'react';
import { shallow } from 'enzyme';
import SomeComponent from './';
describe('SomeComponent', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<SomeComponent></SomeComponent>);
jest.restoreAllMocks();
});
test('should handle button click', () => {
const logSpy = jest.spyOn(console, 'log');
expect(wrapper.find('button')).toHaveLength(2);
const mEvent = { target: { parentNode: { getAttribute: jest.fn().mockReturnValueOnce('id1') } } };
wrapper.find('#id1').simulate('click', mEvent);
expect(logSpy).toBeCalledWith('do something');
expect(mEvent.target.parentNode.getAttribute).toBeCalledWith('id');
});
test('should handle button click', () => {
const logSpy = jest.spyOn(console, 'log');
expect(wrapper.find('button')).toHaveLength(2);
const mEvent = {
target: {
getAttribute: jest.fn().mockReturnValueOnce('id2'),
parentNode: { getAttribute: jest.fn() }
}
};
wrapper.find('#id1').simulate('click', mEvent);
expect(logSpy).toBeCalledWith('do another thing');
expect(mEvent.target.getAttribute).toBeCalledWith('id');
});
});
Результат модульного теста:
PASS src/stackoverflow/58457004/index.spec.tsx
SomeComponent
✓ should handle button click (16ms)
✓ should handle button click (3ms)
console.log node_modules/jest-mock/build/index.js:860
do something
console.log node_modules/jest-mock/build/index.js:860
do another thing
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 83.33 | 100 | 100 | |
index.tsx | 100 | 83.33 | 100 | 100 | 12 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 4.139s, estimated 8s