首页 > 解决方案 > 测试组件中的功能

问题描述

尝试使用 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');
    });
    });

标签: javascriptnode.jsreactjsjestjs

解决方案


你很近。

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

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
  });
});

推荐阅读