I'm trying to test a default prop which is a function type but not sure how to do that with Jest mocking or spying:
Trying following test:
it("should call default toggle function prop on click of footer button", () => {
const wrapper = shallow(
<InfoModal
isOpen={true}
message="Primary message"
secondaryMessage="Secondary message"
/>
);
const footerButton = wrapper.find("ModalFooter Button");
const fn = jest.spyOn(wrapper.props(), "toggle");
footerButton.simulate("click");
wrapper.update();
expect(fn).toHaveBeenCalled();
});
It says TypeError: Cannot assign to read only property 'toggle' of object '[object Object]' where toggle is a function as default prop of InfoModal
.
How can we test a function prop which has been set default not user defined.
You can access the defaultProps like static props;
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
App.defaultProps = {
check: () => console.log('i am working')
}
App.defaultProps.check()
Edited:
You could spy on that like so;
const spy = jest.spyOn(App.defaultProps, 'check');
const RenderedApp = shallow(<App />);
RenderedApp.simulate('click');
expect(spy).toHaveBeenCalled();
So change this line
const fn = jest.spyOn(wrapper.props(), "toggle");
To
const fn = jest.spyOn(wrapper.defaultProps, "toggle");
Will do the trick for you.
https://codesandbox.io/s/zen-morning-881ny
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With