Test React Component Methods with Enzyme

Tyler Clark
InstructorTyler Clark

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

In this lesson we will write tests against a method that lives on our class component. We will access it with the enzyme's instance function and assert that the return values work with the correct arguments.

Instructor: [00:00] As our component grows and becomes more functional, there are times when we may need to add helper methods to the class, methods that are called in lifecycles after user interaction or just to break down more complex functionality.

[00:14] Let's get to bottom here and add a new task for a function that we'll create. Let's say it HandleStrings function returns correctly. Inside this block, we have const wrapper equals shallow our app components. We'll say const with to return equals wrapper.instance.HandleStrings, Hello World as a parameter. Expect true return to be true.

[00:37] Now, at first glance, when we get our terminal, we'll see that is failing because HandleStrings does not exist on this component yet.

[00:47] We're able to access methods on this class because of enzyme's instant function. It returns the component that we've shadowed rendered, and give this access to its properties.

[00:56] Now, let's go to our app file and add this HandleStrings method, which takes the string, and for now, or just return true. This is enough to make all of our tests pass.

[01:08] Let's do a little more with this function and we'll do const FalseReturn=wrapper.instance.HandleStrings. We'll do an empty string this time. We'll except that FalseReturn is false.

[01:21] Now, if we save this, we can see that our test will fail. We want false but we're getting true. Instead of app.js, let's modify our HandleStrings where if the string is Hello World, we want to return true. Else, we'll return false. I want to save this and grab our terminal. This will pass all of our tests.

[01:43] Again, by using the instance method on our wrapper, we are able to grab properties from our class like the HandleStrings function. We can pass different arguments and assert that it works as intended.