/ React

Testing React Components Tricks

When I'm writing test, I have a couple of goals:

  • keep tests simple and understandable
  • only test the important characteristics
  • try to make future-proof as possible

Here are some of the tricks, I use to accomplish those goals.

Most of the components, I write follow the "Component Folder Pattern". Where I have something like the following:

/components/CustomComponent/index.js - component itself
/components/CustomComponent/index.test.js - test file
/components/CustomComponent/styles.css - styles for this compoennt
/components/CustomComponent/SubComponent.js - any subcompoennts
/components/CustomComponent/Fragment.graphq - GraphQL fragment
/compoennts/CustomComponent/... - other things related to this component

I like this pattern a lot. Especially for tests, since you can find the unit test for a specific component quite easy. One other benefit is that, when you rename the component you don't have to rename its test file.

My tests usually look something like this:

// I don't use  the actual component name, in this way 
// when you rename the component, no test change is required
import Component from './index'; 

// future proving, I use `Component.name`, 
// so your test always show the correct component name
// (this works for normal functions as well)
describe(Component.name, () => {
   // I use SUD (system under test) wrapper component for the tests
   // in this way each test contains only the props, specific to a test case
   const defaults = {
     // some default properties
   };
   const SUD = (props) => <Component {...defaults} {...props} />;
   
   it('renders something when someProp is given', () => {
     // this test only cares about `someProp`
     const wrapper = render(<SUD someProp={"value"} />);
     // ... rest of the test
   });
});

I format my it test description in the following format:

it('[action]')
it('[action] when [condition]')
it('can [action] when [condition'])

Here are some examples:

it('renders a form')
it('renders error messages when invalid data is given')
it('can submit a form when valid data is given')

If you want to learn more about the terminology you can check out the slides from my recent talk "Testing in Javascript" at Tech Talks.