javascript - 测试组件内的功能

标签 javascript node.js reactjs jestjs

尝试使用 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/

相关文章:

javascript - 如何使用 web pack 在 React JS 中从外部 JS 文件导入对象

javascript - 如何在我的 React Typescript 计数器中使用类型接口(interface)来支持钻取?

javascript - 打印时调整 Google map 大小

javascript - 413 有效载荷太大,在 express 中调整大小后用于 base64 字符串

node.js - 从 Node.js 中的 websocket 数据源读取 JSON 数组

javascript - 使用nodejs tcp服务器接收客户端数据

javascript - jquery every() 迭代

javascript - 使用带有提交按钮和重置按钮的 JavaScript 计算表单中的两个字段

node.js - 如何安装 sequelize.js 二进制文件?

javascript - 使用 useState hook 的 React 组件是否会在每次 `setState` 调用时重新渲染?