我正嘗試使用酶對組件進行單元測試淺顯示。試圖測試組件的狀態activeTab,並拋出TypeError: Cannot read property state
。我的組件Accordion。 Accordion組件JSX代碼使用酶的反應測試類型錯誤:無法讀取未定義的屬性'狀態'
class Accordion extends Component {
constructor(props) {
super(props)
this.state = {
activeTab: 0
}
}
static defaultProps = {
tabs: [{title: 'Status'}, {title: 'Movement'}]
}
render() {
const { tabs } = this.props
, { activeTab } = this.state
return (
<div className={`accordion`}>
{tabs.map((t, i) => {
const activeClass = activeTab === i ? `accordion--tab__active` : ''
return(
<section key={i} className={`accordion--tab ${activeClass}`}>
<header className={`accordion--header`}>
<h4 className={`accordion--title`}>
<button onClick={() => {this._selectAccordion(i)}}>{t.title}</button>
</h4>
</header>
<div className="accordion--content">
{t.title}
Content
</div>
</section>
)
})}
</div>
)
}
_selectAccordion = activeTab => {this.setState({activeTab})}
}
export default Accordion
和Accordion.react.test.js
import { shallow } from 'enzyme'
import Accordion from './components/Accordion'
test('Accordion component',() => {
const component = shallow(<Accordion name={`Main`}/>)
expect(component.state('activeTab')).equals(0)
})
測試運行良好,我的電腦上,但我必須要改變'.equals(0)'到'.toEqual(0)'。也許你可以共享更多的調試信息,比如酶/節點版本,或者至少粘貼完整的錯誤信息 - 你粘貼的信息只有信息的一半。 – AVAVT
您是否在Jsx文件中導入REACT? –
是的,我在'jsx'文件中導入了React。 –