2016-12-17 118 views
16

我試圖單元測試我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 
+0

你爲什麼兩次導出您的組件瞭解更多關於測試組件的方法呢? – Swapnil

+0

以避免錯誤 –

回答

19

你幾乎在那裏。只要改變你的期望是:

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

你可以通過使用this link

+0

你好,非常感謝你的解決方案,它也幫了我很多。 您是否知道是否有一種方法可以在不使用酶的情況下使用純玩笑測試組件功能? –