を使用していますリアクト/酵素成分をレンダリング私は例のために、このようになっていることを、私は酵素でテストしてるの成分に反応している:浅いは、参考文献
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
私はモカを使用して、いくつかのユニットテストを書いています/チャイ/酵素と私は私の小道具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:未定義のプロパティ 'classList'を読み取ることができません。
私はこれを浅いレンダリングユニットテストとして残し、このコンポーネントをmountで深くレンダリングしたくないので、jsdomのようなブラウザのようなenvを使用する必要があります。
ありがとうございました。
良い提案。私は状態管理のためにReduxを使用しているので、おそらく私の上位のreact-redux 'connect()'コンポーネントにクラスの正しいリストを構築することができます。私はそれに渦巻きの感謝を与えるでしょう。 – Michael
@マイケル、私はこの目的のために、あなたがレフィックスを使っていても地元の州を持つことができると思います。 Ex。 'this.state = {isVisible = false}'とすると、 'button'をクリックするとこの状態変数と' render'関数を切り替えます。この変数に応じて対応するクラスが表示されます。 – 1ven
私はこれをステートレスのプレゼンテーションコンポーネントにしておきたいので、上から管理されている 'show'プロップを渡して、結果として' this.props 'に基づいてコンポーネント内に正しいクラスを表示することができます。ショー。 – Michael