1
我有一個簡單的反應組分,我想測試。它通過道具收回回調。Enzime反應組分測試(淺)
<AnimalSelector onSearchTermChange={Search} />
它看起來如下:
import React, { Component } from 'react';
class SexSelector extends Component {
constructor(props){
super(props);
this.state = {sex: ''};
}
render(){
return (<div>
<input type="radio" name="sex" value="male" id="male" checked={this.state.sex === 'male'} onChange={event => this.onInputChange(event.target.value)} />
<label>Male</label>
<input type="radio" name="sex" value="female" id="female" checked={this.state.sex === 'female'} onChange={event => this.onInputChange(event.target.value)} />
<label>Female</label>
</div>);
}
onInputChange(animal){
this.setState({sex});
this.props.onSearchTermChange(sex);
}
};
export default SexSelector
我寫了一個簡單的測試來檢查的時候可以選擇改變:
import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import {shallow} from 'enzyme';
import SexSelector from '../components/animal_selector';
it('male option changes state sex to male',() => {
const wrapper = shallow(<SexSelector onSearchTermChange="void()"/>);
// manually trigger the callback
wrapper.instance().onInputChange('male');
expect(wrapper.state().sex).toBe('male');
});
然而,測試運行引發以下錯誤:
TypeError:this.props.onSearchTermChange不是函數
at SexSelector.onInputChange (src/components/sex_selector.js:20:15)
at Object.<anonymous> (src/test/sexSelector.test.js:31:22)
at node_modules/p-map/index.js:42:16
at process._tickCallback (node.js:369:9)
Jest/Enzime可以在沒有父級的情況下測試組件嗎?這是繞過回調的正確方法嗎?這是正確的方法嗎?
它引發以下錯誤: 類型錯誤:expect.createSpy是不是對象的函數 。(SRC /測試/ animalSelector.test.js:38:20) 在node_modules /對地圖/ index.js:42:16在 process._tickCallback(node.js中:369:9) 然而,我嘗試了以下方法,您怎麼看? ()); 它('狗的選項改變狀態動物到狗',()=> {0} {wrapper = shallow( {}} />); wrapper.instance()。onInputChange 'dogs'); expect(wrapper.state()。animal).toBe('dogs'); }); –
@ grahamo'donnel這不是很健壯,你手動觸發事件而不是模擬它。我不知道你爲什麼得到這個錯誤,我發佈的是正確的。試試看[期望文檔](https://github.com/mjackson/expect)。 –