Houssin Kareem
Houssin Kareem

Reputation: 21

How to use jest.spyOn with functional react component

I want to test if the handleAddBookToCart function is called when I clicked on the button using Jest.spyOn.

Thank you in advance for your help.

const HomeComponent = props => {
    const { addBookToCart } = props;

    const handleAddBookToCart = id => {
       addBookToCart(id);
    };

    return (
        <button onClick={() => handleAddBookToCart(id)}></button>
    )
}

//Container
const mapDispatchToProps = dispatch => ({
    addBookToCart: idBook => dispatch(cartOperations.addBookToCart(idBook))
});

//file test
describe('Test home component', () => {
   let container;
   let wrapper;
   let component;

   beforeEach(() => {
       wrapper = mount(
           <Provider store={store}>
               <HomeContainer />
           </Provider>
    );
    container = wrapper.find(HomeContainer);
    component = container.find(HomeComponent);

it('calls the handleAddBookToCart function when the button is clicked', () => {
    const spy = jest.spyOn(???)
    component.find('button').simulate('click');
    expect(spy).toHaveBeenCalled();
});

Upvotes: 2

Views: 1873

Answers (2)

Moinul Hossain
Moinul Hossain

Reputation: 2206

Should you must use spyOn? You can just pass a jest mock fn as the addBookToCart prop


it('calls the handleAddBookToCart function when the button is clicked', () => {
   const props = {
     addBookToCart: jest.fn(),
     ...your other props
   }
   const component = shallow(<HomeComponent {...props} />)
    component.find('button').simulate('click');
    expect(props.addBookToCart).toHaveBeenCalled();
});

Upvotes: 2

JoelAK
JoelAK

Reputation: 370

An easy way would be to send a mock into the property addBookToCart and spy on that when the button is clicked.

So when you create/mount/shallow your component for the unit test, try the following (mount coming from enzyme but feel free to use your existing method of testing components):

const spy = jest.fn();
const component = mount(<HomeComponent addBookToCart={spy} />);

Upvotes: 1

Related Questions