我在父组件中有一条愉快的测试路径,它将呈现一个组件或p标签。我对如何测试子组件是否被渲染一无所知。这是我的父组件。
if (startDate && endDate && startDate <= endDate) {
return (
<div className={styles.root}>
<DateRangeInput {...this.props} />
<DateRangePicker
startDate={moment(startDate)}
endDate={moment(endDate)}
onChange={this.onDatePickerChange}
mode={DateRangePicker.MODE_RANGE}
/>
</div>
);
}
return (
<div className={styles.root}>
<DateRangeInput {...this.props} />
<p>Cannot have start date after end date</p>
</div>
);
这是我的测试。我不确定是否要以错误的方式进行操作,还是不确定测试if语句的最佳做法
describe('<DateRangeInputPicker />', () => {
it('should show null messaging when endDate < startDate', () => {
const { getByText } = render(
<DateRangeInputPicker
startDate={new Date(2018, 0, 14)}
endDate={new Date(2017, 1, 29)}
onChange={jest.fn()}
/>
);
expect( getByText('Cannot have start date after end date')).toBeInTheDocument();
});
it('should render DateRangePicker when endDate > startDate', () => {
const { getByText } = render(
<DateRangeInputPicker
startDate={new Date(2018, 0, 14)}
endDate={new Date(2017, 1, 29)}
onChange={jest.fn()}
/>
);
});
});
答案 0 :(得分:2)
如果您打算测试组件的生命周期以及如何根据更新进行呈现,则应该考虑在Jest的测试环境中实现Enzyme。
这段代码将测试您要实现的目标。如果您不熟悉酶,那么互联网上有很多课程,教程和博客文章。
import React from 'react';
import { shallow } from 'enzyme';
import DateRangeInputPicker from './DateRangeInputPicker';
describe('DateRangeInputPicker', () => {
const component = shallow(<CreateTask />);
describe('when endDate < startDate', () => {
beforeEach(() => {
// Any code here to make your component come to that condition
});
it('should show a message', () => {
const message = component.find('p'); // would be better to use an id or class selector
expect(message.text()).toBe('Cannot have start date after end date');
});
});
});
无论如何,我将尽力解释您应该做什么。