Categories
React Answers

How to Check if a Function is Called on a Component Jest?

Spread the love

Sometimes, we want to check if a function is called when we do something in our React component test.

In this article, we’ll look at how to check if a function is called when we do something in our React component test with Jest.

Check if a Function is Called on a Component Jest

To check if a component’s method is called, we can use the jest.spyOn method to check if it’s called.

For instance, we can write the following test:

describe('simple test', () => {
  it('clicks it', () => {
     const app = shallow(<App />)
     const instance = app.instance()
     const spy = jest.spyOn(instance, 'onClick')
     instance.forceUpdate();

     const p = app.find('.button')
     p.simulate('click')
     expect(spy).toHaveBeenCalled()
 })
})

We check if the onclick method is called if we get the p element and call it.

First, we mount the App component with the shallow function.

Then we get the instance with the instance method.

Next, we call jest.spyOn on the component method that we expect to call if we click the button.

We call forceUpdate to update our component that we want to test with the spy.

Then we find the p element with the class button .

Then we call simulate('click') on that to click it.

And then we check if the mock function has been called.

This works for class components since they have instance methods.

How to set the Inline Style of background-color with React

We can set the inline style of background color with the backgroundColor property.

For instance, we can write:

<a style={{ backgroundColor: 'orange' }}>orange</a>

We set the backgroundColor to 'orange' with the camel-cased key.

Conclusion

To check if a component’s method is called, we can use the jest.spyOn method to check if it’s called.

One reply on “How to Check if a Function is Called on a Component Jest?”

Leave a Reply

Your email address will not be published. Required fields are marked *