The React Shallow Renderer test utility lets us inspect the output of a component one level deep. In this lesson, we will examine the rendered output of props, specifically the className
prop. We will then use the ES2015 String.includes()
method to check that our rendered className includes what we expect.
Hi, I found this course very useful. One thing I'm wondering, are these real tests that you would write in a production app? To me it seems like this would almost never break, unless there was a dramatic update in React OR in your testing library.
https://github.com/trevordmiller/favorite-quotes/blob/master/src/components/Icon.spec.js
Tests not breaking is a feature, generally. Catching React update issues is definitely a solid use case for a test.
Gotcha, I'm just wondering if there is any real business value here.
This is a great example of shallow rendering but at it's core it seems like it is really testing that this.props.string = string
which isn't hugely valuable on its own.
I'm pretty new to testing in general and I guess I'm just asking in general if it's really worth testing and maintaining a use case like this.
Clinton, I think the key to a useful test is that you are testing something that you want to ensure doesn't break without you knowing about it. In the lesson, we look at testing that a string of classnames contains a specific substring to ensure that our icons will be rendered correctly; this is not this.props.string = string
but rather this.props.string.includes('substring')
. In this situation, the value comes in knowing that our icons are rendering correctly - and we don't have to manually check this in the browser any time we make a change to the Icon component.
There are hundreds of other use cases for this, but the principle is that we...
I've found generic tests like this to be very useful :)
"To me it seems like this would almost never break, unless there was a dramatic update in React OR in your testing library."
This is the beauty of it! The only time this test would break is if we screw up our Icon component where it is no longer rendering the correct Icon types - which is what we want. If the test did break we would want to know about it before our users complain "the icons aren't working anymore". The test provides value because it will let us know immidiately if we have broken our key expected functionality in our component without having to manually check the component output in the browser every time we make a change.
Although the example in this lesson is small and simple, the more tests you have like this, the easier it is to add new features and refactor with confidence, which is the true value of testing.
expect
has a toInclude
method that you could use directly!
Hey Concierge. Using the expect-jsx methods gives you nice JSX syntax error diffs. Not required but I find it much easier to debug :)