Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on default prop function in Jest

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.

like image 728
Manish Jangir Avatar asked Oct 15 '22 10:10

Manish Jangir


1 Answers

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

like image 113
Miller Avatar answered Oct 21 '22 08:10

Miller