B
B
bpGusar2018-10-03 16:50:04
React
bpGusar, 2018-10-03 16:50:04

How to test a function in React via Jest?

The function is inside a class, for example:

class Bla extends React.Component {
public Foo = (arg) =>{
// тут че нибудь делаем
} 
render(){
...
}
}

How to test it? I just started to study testing and ran into a wall, xs how can it be. That is, it must be exported, and then imported into the test file? Or how? What is the right thing to do?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Javid Askerov, 2018-10-03
@HalfBloodPrince

I will answer within the framework with which I am familiar, as I test and see it. It makes no sense to test methods in a react component. I'm thinking of approaching this, testing how the class will be used. If this method will be used separately somewhere, then you need to think about testing it, if not, then its purpose as a component is the render function.
For this, there are libraries like react-testing-library (there was an article about it and on Habré), as well as Enzyme. The bottom line is that you render your component in a test and see that it produces the correct results. And what it does inside is the business of the component.
With the help of coverage jest, you can see which methods were used under the conditions of your test. For example, if the method is called after clicking on some element inside the component, then you can use the appropriate trigger in the test and "click" there and make sure that the desired changes have occurred.
If this method does some important logic, then it might be worth overriding it outside the essence of the react, creating a separate class or function and testing it separately.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question