reactjs-如何对React组件的方法进行单元测试?

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

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

刚开始时,我已经在努力声明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
bier hier asked 2020-06-26T10:43:47Z
3个解决方案
58 votes

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

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

您可以通过此链接了解有关使用酶测试组分方法的更多信息。

Swapnil answered 2020-06-26T10:44:05Z
8 votes

对于那些发现接受的答案无效的人,请尝试在浅层包装上使用.dive(),然后再使用.instance()

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

参考:使用酶测试组成方法

Or A. answered 2020-06-26T10:44:29Z
0 votes

扩展先前的答案。如果已连接组件(Redux),请尝试以下代码:

 const store=configureStore();
  const context = { store };
   const wrapper = shallow(
      <MyComponent,
      { context },
    );
   const inst = wrapper.dive().instance();
   inst.myCustomMethod('hello');
Serhii Bilyk answered 2020-06-26T10:44:49Z
translate from https://stackoverflow.com:/questions/41196561/how-to-unit-test-a-method-of-react-component