Reputation: 7460
I have a test that needs to check for a function being called within another function attached to a button with jest and enzyme. I have both functions mocked out, but don't know how to attach one to another.
My component looks like the following:
class MyComponent extends React.Component {
handleButton () {
console.warn('Clicked!')
this.context.anotherFunction()
}
render () {
return (
<div>
My Component
<button class='my-button' onClick={handleButton}>My Button</button>
</div>
)
}
}
I want to check that both onClick
and this.context.anotherFunction
are called when the button is clicked. This is what my current test looks like:
test.only('should test MyComponent button', () => {
const wrapper = shallow(<MyComponent {...props} />)
const anotherFunction = jest.fn()
wrapper.instance().context = { anotherFunction }
wrapper.instance().handleButton = () => {
jest.fn()
// How to simulate a call to anotherFunction???
// wrapper.instance().context.anotherFunction()
}
wrapper.find('.my-button').simulate('click')
expect(wrapper.instance().showCancelModal).toHaveBeenCalled() // Passes
expect(wrapper.instance().context.showModal).toHaveBeenCalled() // Fails
})
How can I mock the call of anotherFunction
in the mocked version of handleButton
?
Upvotes: 1
Views: 1501
Reputation: 1061
What you probably want is jest.spyOn()
That allows you to monitor calls to a function without actually mocking it. So what will be able to do is:
test.only('should test MyComponent button', () => {
const wrapper = shallow(<MyComponent {...props} />)
const anotherFunction = jest.fn()
wrapper.instance().context = { anotherFunction }
const handleButton = jest.spyOn(wrapper.instance(), 'handleButton');
wrapper.find('.my-button').simulate('click')
// your tests:
expect(handleButton).toHaveBeenCalled() // Passes
// Instead of checking "wrapper.instance().context.anotherFunction"
// you can directly check if anotherFunction was called
expect(anotherFunction).toHaveBeenCalled() // Fails
})
Upvotes: 1