【问题标题】:testing a function within a component测试组件中的功能
【发布时间】: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() 方法的事件间接触发该方法,然后在执行后检查结果。例如,如果它由于该组件上某个按钮上的单击事件而触发,则要触发/模拟单击然后验证 orderorderBy 状态值是否已按预期更新。
  • 传入另一个组件 onRequestSort={this.handleRequestSort}
  • 查看答案。您可以有效地找到子组件,执行绑定到该子组件的相应 prop 函数,然后验证结果(状态如您所愿更改)。

标签: javascript node.js reactjs jestjs


【解决方案1】:

你已经接近了。

这是一个基于您提供的代码的工作示例:

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 16 及更高版本中,instance() 为无状态功能组件返回 null。 link.
猜你喜欢
  • 2020-12-18
  • 2020-07-17
  • 1970-01-01
  • 2021-08-18
  • 2019-08-06
  • 2021-08-30
  • 2021-09-04
  • 2016-08-09
  • 1970-01-01
相关资源
最近更新 更多