javascript - 如何在 React 中测试类组件

标签 javascript reactjs jestjs

我正在尝试一些单元测试,我创建了一个带有假示例的沙箱 https://codesandbox.io/s/wizardly-hooks-32w6l (实际上我有一个表格)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { number: 0 };    
  }

  handleSubmit = (number1, number2) => {
    this.setState({ number: this.handleMultiply(number1, number2) })
  }

  handleMultiply = (number1, number2) => {
    return number1 * number2
  }

  render() {
    const { number } = this.state;

    return (
      <div className="App">
        <form onSubmit={e => this.handleSubmit(3, 7)}>       
          <input type="submit" name="Submit" value="Multiply" />
        </form>
        <Table number={number} />
      </div>
    );
  }
}

export default App;

所以我最初的想法是尝试测试乘法函数。并这样做了,这显然不起作用

import App from "../src/App";

test("Multiply", function() {
  const expected = 21;
  const result = App.handleMultiply(3, 7);
  expect(result).toBe(expected);
});

我明白了

_App.default.handleMultiply is not a function

我的做法对吗?如果是的话我该如何测试这些功能?否则,我应该从用户的 Angular 进行测试,而不是内部函数(这是我读到的)?我应该测试屏幕上的输出吗(我认为这不合理)?

最佳答案

您可以使用instance() enzyme 方法来获取 React Component 的实例。然后,直接调用handleMultiply方法并对其进行断言。此外,如果handleMultiply方法有副作用或非常复杂的计算,您需要为其制作一个简单的模拟返回值。它将为 handleSubmit 方法创建一个隔离的测试环境。这意味着handleSubmit方法将不依赖于handleMultiply方法实际实现的返回值。

例如

app.jsx:

import React from 'react';
import { Table } from './table';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { number: 0 };
  }

  handleSubmit = (number1, number2) => {
    this.setState({ number: this.handleMultiply(number1, number2) });
  };

  handleMultiply = (number1, number2) => {
    return number1 * number2;
  };

  render() {
    const { number } = this.state;

    return (
      <div className="App">
        <form onSubmit={(e) => this.handleSubmit(3, 7)}>
          <input type="submit" name="Submit" value="Multiply" />
        </form>
        <Table number={number} />
      </div>
    );
  }
}

export default App;

table.jsx:

import React from 'react';

export const Table = ({ number: num }) => {
  return <div>table: {num}</div>;
};

app.test.jsx:

import App from './app';
import { shallow } from 'enzyme';

describe('59796928', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<App></App>);
  });
  describe('#handleSubmit', () => {
    it('should pass', () => {
      expect(wrapper.exists()).toBeTruthy();
      wrapper.find('form').simulate('submit');
      expect(wrapper.state()).toEqual({ number: 21 });
    });
  });
  describe('#handleMultiply', () => {
    it('should pass', () => {
      const comp = wrapper.instance();
      const actual = comp.handleMultiply(2, 10);
      expect(actual).toBe(20);
    });
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/59796928/app.test.jsx (11.688s)
  59796928
    #handleSubmit
      ✓ should pass (16ms)
    #handleMultiply
      ✓ should pass (9ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |    90.48 |      100 |    85.71 |    94.44 |                   |
 app.jsx   |      100 |      100 |      100 |      100 |                   |
 table.jsx |       50 |      100 |        0 |    66.67 |                 4 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        13.936s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59796928

关于javascript - 如何在 React 中测试类组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59796928/

相关文章:

javascript - 来自 json 对象的 Highcharts 堆叠列

javascript - 从光标位置应用悬停

reactjs - Antd 中的固定宽度列?

javascript - React 测试库 - fireEvent 不会更改输入值

reactjs - React + Jest + Enzyme 表单 onSubmit 测试失败,除非我使用超时

javascript - 当数组中的函数之一不返回 Promise 时,我可以使用 $q.all 吗?

javascript - 有没有手动设置backbone模型不变的接口(interface)?

reactjs - react 路由器 : Show progress while loading

reactjs - React this.props 未定义

javascript - React+Typescript+Webpack项目中Jest配置错误