javascript - 测试组件中的功能
问题描述
尝试使用 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
});
});
推荐阅读
- react-native - 安装样式组件在本机反应中失败
- excel - 如何在excel公式中找到截止日期?
- typescript - Typescript Object.entries 和映射类型
- elasticsearch - Kibana Dashboard 说找不到那个索引模式
- html - 如何在点击 div 时在电子 js 中打开菜单
- python - 如何用列表中的值替换 url 中的值并使用 FOR 循环遍历它们
- node.js - 我应该使用哪个 HTTP 动词来删除 MongoDB 子文档?
- python-3.x - 如何使用混淆矩阵评估 NMF 主题建模?
- c++ - 数组中的 C++ 等号运算符
- git - 将旧分支上的新提交合并到 dev