【发布时间】:2019-07-22 21:59:35
【问题描述】:
尝试使用 jest 为以下函数编写单元测试,到目前为止,我一直在将函数导出到类之外进行测试,我现在的问题是函数在类中,我不知道如何正确测试它。 下面的 handleRequest 在一个类中
handleRequestSort(event, property) {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
}
describe('Test for handleRequestSort', () => {
it('should handle the sorting of a request', () => {
const ordering = Contract.handleRequestSort(null, 'name');
expect(ordering).toEqual('name');
});
});
【问题讨论】:
-
describe('Test for handleRequestSort', () => { it('should handle the sorting of a request', () => { const wrapper = shallow(<ContractTable />); wrapper.instance().handleRequestSort(null, 'name'); expect(wrapper).toEqual('name'); }); });尝试过类似的方法,但无济于事 -
handleRequestSort()究竟是如何被组件实例执行的?关键是通过内部调用该组件实例的handleRequestSort()方法的事件间接触发该方法,然后在执行后检查结果。例如,如果它由于该组件上某个按钮上的单击事件而触发,则要触发/模拟单击然后验证order、orderBy状态值是否已按预期更新。 -
传入另一个组件 onRequestSort={this.handleRequestSort}
-
查看答案。您可以有效地找到子组件,执行绑定到该子组件的相应 prop 函数,然后验证结果(状态如您所愿更改)。
标签: javascript node.js reactjs jestjs