我有一个React组件,我正在使用Enzyme进行测试,例如,这样看起来像这样:
import React, {Component} from 'react'
class Foo extends Component {
constructor(props) {
super(props)
this.showContents = this.showContents.bind(this)
}
showContents() {
this.button.classList.toggle("active")
this.button.nextElementSibling.classList.toggle("show")
this.props.onRequestShowContents()
}
render() {
return (
<div className="wrapper">
<button ref={(ref) => this.button = ref} onClick={this.showContents}>Click to view contents</button>
<div className="panel">
{this.props.contents}
</div>
</div>
)
}
}
export default Foo
我正在使用Mocha / Chai / Enzyme编写一些单元测试,我想模拟按钮按下来检查我的道具func被调用 .
我的基本酶测试看起来像这样:
import React from 'react'
import { shallow } from 'enzyme'
import Foo from '../components/Foo'
import chai from 'chai'
import expect from 'expect'
var should = chai.should()
function setup() {
const props = {
onRequestShowContents: expect.createSpy(),
contents: null
}
const wrapper = shallow(<Foo {...props} />)
return {
props,
wrapper
}
}
describe('components', () => {
describe('Foo', () => {
it('should request contents on button click', () => {
const { props, wrapper } = setup()
const button = wrapper.find('button')
button.props().onClick() //this line causes the error
props.onRequestShowContents.calls.length.should.equal(1)
})
})
})
有什么方法可以调整测试或我的组件代码,以避免在单击处理程序中访问 this.button
时出错?我得到"TypeError: Cannot read property 'classList' of undefined" .
我希望将其保留为浅渲染单元测试,并且不希望使用mount深度渲染此组件,这需要使用类似浏览器的env,例如jsdom .
谢谢 .
1 回答
我认为这是不可能的 .
浅呈现docs没有
ref
属性的文档 . 但是挂载渲染docs有它 .另外,你可以查看github issue .
在我看来,要不使用装载渲染,而不是访问
classList
和nextElementSibling
,请设置相应的状态变量并根据此变量显示所需的classNames .