2017-04-21 48 views
0

我有一個LoginInfo組件,在這個組件下我調用了一個更多的子組件。我正在嘗試使用笑話,酶和反應測試工具編寫單元測試用例。部分我已經寫了測試用例,但不知道如何編寫測試的子組件(LoginInfoEdit)。那條線我無法覆蓋。Reactjs單元測試

import React from 'react'; 
import { LoginInfoEdit } from './LoginInfoEdit' 

class LoginInfo extends React.Component { 
constructor(props) { 
    super(props) 
    this.state = { 
     isLoginInfo: false 
    } 
} 
openEdit() { 
    this.setState({ isLoginInfo: true }) 
} 

closeEdit() { 
    this.setState({ isLoginInfo: false }) 
} 
OpenEditForUpdate(e) { 
    e.preventDefault(); 
    this.openEdit(); 
} 
render() { 
    return (
     <div> 
      <form>      
       <div> 
        some text 
       </div> 

       <LoginInfoEdit loginid={this.props.loginid} openloginedit={this.state.isLoginInfo} onClose={this.closeEdit.bind(this)}>       
       </LoginInfoEdit> 
      </form> 
     </div> 
    ) 
} 
} 
export default LoginInfo 

單元測試是下面--------

import React from 'react' 
import { shallow } from 'enzyme'; 
import LoginInfo from './LoginInfo' 
import LoginInfoEdit from './LoginInfoEdit' 

const props = { 
loginid: "1", 
openloginedit: false, 
}; 
describe('LoginInfo component',() => { 
let LoginInfo = null; 
let editButton = null; 

beforeEach(() => { 
    LoginInfo = shallow(<LoginInfo {...props}/>); 
    editButton = LoginInfo.find('button[name="edit"]') 
}) 

it('checks everything set properly',() => { 
    editButton.simulate('click', { preventDefault:() => { } }); 
    expect(LoginInfo.state('isloginedit')).toEqual(true) 
}) 
it('renders child',() => { 
    expect(LoginInfo.find('LoginInfoEdit').length).toEqual(1) 
}); 
it('passes proper props to the child',() => { 
    const expected = { 
    loginid: "1", 
    openloginedit: false, 
    onClose: LoginInfo.instance().closeEdit.bind(this), 
}; 

expect(LoginInfo.find('LoginInfoEdit').props()).toEqual(expected) 
}) 
}) 

回答

1

通常在這樣的情況下,我只關心我們檢查是否使兒童和傳遞我們想要的道具像孩子:

let component; 

const props = someProps; 

beforeEach(() => { component = mount(<LoginInfo { ..props } />); }); 

it('renders child',() => { 
    expect(component.find('LoginInfoEdit').length).to.eql(1) 
}); 

it('passes proper props to the child',() => { 
    const expected = { 
    loginid: someVal, 
    openloginedit: someotherVal, 
    onClose: component.instance().closeEdit, 
    }; 

    expect(component.find('LoginInfoEdit').props()).to.eql(expected) 
}); 

,然後我就從父測試孩子(在這種情況下,LoginInfoEdit)分別

+0

謝謝您的回答BU接收和預期是不同的預期我越來越 - 「onClose」:[函數closeEdit],並在收到我越來越 - 「onClose」:[函數onClose],所以它不是matxing。由於此測試從輸出中失敗 – user2768132

+0

,因此您似乎將不同的函數或不同的函數名稱傳遞給預期的對象。 – beniutek

+0

感謝您的答覆。從輸出似乎,但我傳遞像例如提到的喲相同的名稱..但出現錯誤後,我改變它onClose:component.instance()。closeEdit.bind(this)。然後我得到「差異:比較值沒有視覺差異。」錯誤。測試用例失敗。不知道是什麼問題。 – user2768132