Вы можете использовать setState метод enzyme
для изменения состояния вашего компонента.Ниже приведено решение только для тестирования метода render
независимо без simulate
события.
index.tsx
:
import React from 'react';
interface ICheckStateState {
isDone: boolean;
}
export class CheckState extends React.Component<{}, ICheckStateState> {
constructor(props) {
super(props);
this.state = {
isDone: false
};
}
public render() {
if (this.state.isDone) {
return <div>Done</div>;
} else {
return <div>Not Done</div>;
}
}
}
index.spec.tsx
:
import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { CheckState } from './';
describe('CheckState', () => {
describe('#render', () => {
let wrapper: ShallowWrapper;
beforeEach(() => {
wrapper = shallow(<CheckState></CheckState>);
});
it('should render correctly', () => {
expect(wrapper.exists()).toBe(true);
expect(wrapper.text()).toBe('Not Done');
wrapper.setState({ isDone: true });
expect(wrapper.text()).toBe('Done');
});
});
});
Результат модульного теста со 100% покрытием:
PASS src/stackoverflow/58059957/index.spec.tsx
CheckState
#render
✓ should render correctly (8ms)
-----------|----------|----------|----------|----------|-------------------|
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: 2.819s, estimated 6s