React.Component
に拡張されたクラスの関数をモックするためにEnzymeとJestを使って単体テストをしようとしていますが、継承したsetState
関数を模倣することができますが、コンポーネント内にあります。例えばReactネイティブコンポーネントとモザイク関数
、私のアプリのコンポーネントがonChangeText
イベントにsetState
を呼び出しTextInput
を持ち、かつonPress
イベントにsubmitFilter
を呼び出しTouchableOpacity
。
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = { filter: '' }
}
submitFilter =() => {
if (this.state.filter.length <= 0) {
Alert.alert('Filter is blank');
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.filterContainer}>
<TextInput
style={styles.filterInput}
placeholder='Filter...'
value={this.state.filter}
onChangeText={(text) => {this.setState({ filter: text })}}
/>
<TouchableOpacity
style={styles.filterButton}
onPress={this.submitFilter}>
<Text style={styles.filterButtonLabel}>Go</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
setState
とsubmitFilter
をからかうための同じパターンを使用して、各機能を呼び出すための同じパターン:
import Adapter from 'enzyme-adapter-react-16';
import Enzyme from 'enzyme';
Enzyme.configure({ adapter: new Adapter() });
describe('interaction',() => {
let wrapper
let mockFn
beforeEach(() => {
wrapper = Enzyme.shallow(<App />)
mockFn = jest.fn()
})
describe('editing the filter input',() => {
beforeEach(() => {
wrapper.instance().setState = mockFn
wrapper.find('TextInput').first().props().onChangeText('waffles');
})
it('should update the filter state',() => {
expect(mockFn).toHaveBeenCalledTimes(1)
})
})
describe('clicking filter button',() => {
beforeEach(() => {
wrapper.instance().submitFilter = mockFn
wrapper.find('TouchableOpacity').first().props().onPress()
})
it('should invoke the submitFilter callback',() => {
expect(mockFn).toHaveBeenCalledTimes(1)
})
})
})
のみ最初のパス、と私はモックのために使用してどのようなアプローチわからないんだけどsubmitFilter
機能が呼び出されることを確認する機能はありますか?
interaction
editing the filter input
✓ should update the filter state (3ms)
clicking filter button
✕ should invoke the submitFilter callback (18ms)
● interaction › clicking filter button › should invoke the submitFilter callback
expect(jest.fn()).toHaveBeenCalledTimes(1)
Expected mock function to have been called one time, but it was called zero times.
at Object.<anonymous> (App.test.js:47:16)
at tryCallTwo (node_modules/promise/lib/core.js:45:5)
at doResolve (node_modules/promise/lib/core.js:200:13)
at new Promise (node_modules/promise/lib/core.js:66:3)
at tryCallOne (node_modules/promise/lib/core.js:37:12)
at node_modules/promise/lib/core.js:123:15
こんにちは、この回答する@ worldlee78のためのおかげで、私はあなたがやったとして指摘誰が、githubの中の酵素レポに同じ質問を投稿してしまった - HTTPS([プロトタイプのスパイ]へ:// githubの。 com/airbnb/enzyme/issues/1432)、もう一度ありがとう! – erikse
あなたは歓迎です@erikse解決策があなたのために働くなら、あなたは私の答えを正しいものとして選択してもよろしいですか? – worldlee78