【问题标题】:How to unit test a method of react component?如何对反应组件的方法进行单元测试?
【发布时间】:2017-05-02 23:14:29
【问题描述】:

我正在尝试对我的 reactjs 组件进行单元测试:

import React from 'react';
import Modal from 'react-modal';
import store from '../../../store'
import lodash from 'lodash'

export class AddToOrder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {checked: false}
    //debugger
  }
  checkBoxChecked() {
    return true
  }
  render() {
    console.log('testing=this.props.id',this.props.id )
    return (
      <div className="order">
        <label>
          <input
            id={this.props.parent}
            checked={this.checkBoxChecked()}
            onChange={this.addToOrder.bind(this, this.props)}
            type="checkbox"/>
          Add to order
        </label>
      </div>
    )
  }
}

export default AddToOrder;

刚开始我已经在努力断言 checkBoxChecked 方法:

import React from 'react-native';
import {shallow} from 'enzyme';
import {AddToOrder} from '../app/components/buttons/addtoorder/addtoorder';
import {expect} from 'chai';
import {mount} from 'enzyme';
import jsdom from 'jsdom';
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.document = doc
global.window = doc.defaultView

let props;
beforeEach(() => {
  props = {
    cart: {
      items: [{
        id: 100,
        price: 2000,
        name:'Docs'
      }]
    }
  };
});

describe('AddToOrder component', () => {
  it('should be handling checkboxChecked', () => {
    const wrapper = shallow(<AddToOrder {...props.cart} />);
    expect(wrapper.checkBoxChecked()).equals(true); //error appears here
  });
});

```

如何对组件上的方法进行单元测试?这是我得到的错误:

TypeError: Cannot read property 'checked' of undefined

【问题讨论】:

  • 为什么要导出组件两次?
  • 避免错误
  • 可以通过 import {shallow, mount} from 'enzyme' 导入一次;而不是两个进口,一个用于装载,一个用于浅

标签: unit-testing reactjs chai enzyme


【解决方案1】:

你快到了。只需将您的期望更改为:

expect(wrapper.instance().checkBoxChecked()).equals(true);

您可以通过this link了解更多关于使用酶测试组件方法的信息

【讨论】:

  • 您好,非常感谢您的解决方案,它也对我帮助很大。你知道有没有一种方法可以在没有酶的情况下用纯玩笑来测试组件的功能?
  • 嘿@AttilaMolnár 回复很晚,但你应该可以做到MyComponent.prototype.method()。 React 只是将方法附加到prototype
  • 这太棒了!
  • 感谢这样的回答,我能够比以往更多地了解测试 :) 谢谢!
  • @xenetics 实际上不起作用,因为关闭
【解决方案2】:

对于那些认为接受的答案不起作用的人,请在使用 .instance() 之前尝试在浅包装器上使用 .dive()

expect(wrapper.dive().instance().somePrivateMethod()).toEqual(true);

参考:Testing component methods with enzyme

【讨论】:

  • 这只有在你将组件包装在某些东西中时才需要,例如 Redux 连接方法。
【解决方案3】:

上一个答案的扩展。 如果您已连接组件(Redux),请尝试下一个代码:

 const store=configureStore();
  const context = { store };
   const wrapper = shallow(
      <MyComponent,
      { context },
    );
   const inst = wrapper.dive().instance();
   inst.myCustomMethod('hello');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 2019-09-30
    • 2017-10-27
    • 2020-01-20
    • 2020-09-28
    • 2019-03-26
    • 2021-07-29
    • 1970-01-01
    相关资源
    最近更新 更多