我正在使用Mocha,Chai,Nock,Sinon,Webpack进行单元测试。
我使用以下链接来测试我的行为,减少者 http://redux.js.org/docs/recipes/WritingTests.html
我能够测试其他反应文章中的哑组件。目前我正在尝试测试我的智能组件,但我得到了错误。
my react-redux组件(SmartComponent.js)
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import * as componentActions from '../actions/componentActions'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
export class SmartComponent extends Component {
constructor(props) {
super(props)
this.updateText = this.updateText.bind(this)
}
updateText(event){
this.props.actions.updateText(event.target.value)
}
render() {
return(
<div>
<input type='text' onChange={this.action1} placeholder='type something'
/>
<span>{this.props.inputText}
</div>
)
}
}
function mapStateToProps(state) {
const inputText = state.inputText
return{
inputText
}
}
function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(componentActions, dispatch)
}
}
const SmartComponentContainer = connect(
mapStateToProps,
mapDispatchToProps
)(SmartComponent)
module.exports = SmartComponentContainer
这是我的单元测试文件
import setupDom from '../setup'
import chai from 'chai'
import jsxChai from 'jsx-chai'
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'
import {Provider} from 'react-redux'
import {findAllWithType, findWithType, findWithClass} from 'react-shallow-testutils'
import SmartComponentContainer,{SmartComponent} from "../containers/SmartComponent"
chai.use(jsxChai)
let expect = chai.expect
/**
* Mock out the top level Redux store with all the required
* methods and have it return the provided state by default.
* @param {Object} state State to populate in store
* @return {Object} Mock store
*/
function createMockStore(state) {
return {
subscribe: () => {},
dispatch: () => {},
getState: () => {
return {...state};
}
};
}
function setup() {
const storeState={
inputText : ''
}
let renderer = TestUtils.createRenderer()
renderer.render(<SmartComponentContainer store={createMockStore(storeState)} />)
let output = renderer.getRenderOutput()
return {
output,
renderer
}
}
function setUpComponent(){
const props ={}
let renderer = TestUtils.createRenderer()
renderer.render(<SmartComponent {...props} />)
let output = renderer.getRenderOutput()
return {
output,
renderer
}
}
describe('test smart component container',()=>{
it('test input value change',()=>{
const {output,renderer} = setup()
console.log(output)
// when i do the console.log output here , i am getting my actions and state variable but i do not get the html inside render method
})
it('test component',()=>{
const {output,renderer} = setUpComponent()
console.log(output)
})
})
第一次测试成功,我使用动作和状态变量打印输出,但无法打印渲染html。
第二个测试抛出错误“TypeError:无法读取未定义的属性'propTypes'”。我想访问html并且具有与普通组件一样的能力测试
expect(output.props.children[0].type).to.equal('input')