Вот решение для модульного тестирования с использованием дополнительного пакета enzyme
.
index.tsx
:
import React, { useState } from 'react';
export default function MyComponent({ index }) {
const [currentTab, setCurrentTab] = useState(index);
const handleTabChange = (event: React.ChangeEvent<{}>, tab: number) => {
console.log('test handleTabChange: ' + tab);
setCurrentTab(tab);
};
return (
<div>
<select onChange={(e) => handleTabChange(e, 1)}>
<option>chocolate</option>
<option>strawberry</option>
<option>vanilla</option>
</select>
<span>currentTab: {currentTab}</span>
</div>
);
}
index.test.tsx
:
import MyComponent from './';
import React from 'react';
import { shallow } from 'enzyme';
describe('61480694', () => {
it('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
const mProps = { index: 2 };
const wrapper = shallow(<MyComponent {...mProps}></MyComponent>);
expect(wrapper.find('span').text()).toBe('currentTab: 2');
wrapper.find('select').simulate('change');
expect(wrapper.find('span').text()).toBe('currentTab: 1');
expect(logSpy).toBeCalledWith('test handleTabChange: 1');
logSpy.mockRestore();
});
});
модульный тест результаты со 100% покрытием:
PASS stackoverflow/61480694/index.test.tsx (11.97s)
61480694
✓ should pass (28ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
test handleTabChange: 1
-----------|---------|----------|---------|---------|-------------------
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: 13.844s