试图用玩笑为以下功能编写单元测试,直到现在我一直在导出类之外的功能以进行测试,我现在的问题是一个函数在一个类内,我不知道如何正确测试它。 下面的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');
});
});
答案 0 :(得分:0)
您已经关闭。
这是一个基于您提供的代码的有效示例:
import * as React from 'react';
import { shallow } from 'enzyme';
class ContractTable extends React.Component {
constructor(...args) {
super(...args);
this.state = { };
}
handleRequestSort(event, property) {
const orderBy = property;
let order = 'desc';
if (this.state.orderBy === property && this.state.order === 'desc') {
order = 'asc';
}
this.setState({ order, orderBy });
}
render() { return null; }
}
describe('Test for handleRequestSort', () => {
it('should handle the sorting of a request', () => {
const wrapper = shallow(<ContractTable />);
const instance = wrapper.instance();
instance.handleRequestSort(null, 'name');
expect(wrapper.state()).toEqual({ order: 'desc', orderBy: 'name' }); // SUCCESS
instance.handleRequestSort(null, 'name');
expect(wrapper.state()).toEqual({ order: 'asc', orderBy: 'name' }); // SUCCESS
instance.handleRequestSort(null, 'address');
expect(wrapper.state()).toEqual({ order: 'desc', orderBy: 'address' }); // SUCCESS
});
});