尝试使用 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');
});
});
最佳答案
你已经很接近了。
这是一个基于您提供的代码的工作示例:
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
});
});
关于javascript - 测试组件内的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54934974/