Hacker News new | ask | show | jobs
by cjcenizal 3623 days ago
I've found the best testing pattern is to test the interface of the component, not the implementation.

This means treating the component as an opaque function with inputs (props) and outputs (the rendered result). Your tests just need to that verify that different prop values result in the DOM changes or callbacks that you expect.

3 comments

Agree 100%. However if you are using component state you will need to test how interactions impact rendering output on the next render pass. I wouldn't consider that implementation detail since you are only asserting against render output.

In the case of testing instance methods, this is definitely a special edge-case scenario, but actually one of the main reasons I put this together. They inevitably happen, but are rare and I tend to forget how to set those tests up.

To give you an idea of how we use this: our application is a "website designer" where the preview is rendered inside an iframe. We use a react component to push CSS changes directly into the iframe via document.styleSheets. Using instance method testing allows us to test the main output results of this functionality without having to render real iframes pointing to external server in our tests.

I prefer this style of component test and tend to bring in jQuery as a test dependency to remove some of the complexity of the assertions (I'm not always up to date on the current DOM APIs).

I find the instance method unit test a bit unsatisfying. I'm not going to call an instance method of a component from outside of that component (maybe someone else is doing this - I'm just not sure what the use case is), so why would I do that in my test? I want to integrate through the instance method by poking at the DOM rather than calling the method directly.

Do you use any tools to make the assertions on the resulting DOM simpler?

What about any components that maintain internal state; do you just step them through the states and assert the DOM state as well?

I built this testing tool at a previous employer: https://github.com/smaato/react-test-kit. It's very very simple, it just exposes jQuery-like methods for querying the DOM (and internally uses Sizzle).

Here's an example of how we used react-test-kit to test a SearchBox component: https://github.com/smaato/ui-framework/blob/develop/src/fram...

Here's the interactive component example: http://smaato.github.io/ui-framework/#/searchbox

I find it simplest to use shallow rendering in my unit tests as opposed to rendering the DOM, so the output I have to verify only contains things the component-under-test renders.

As for shallow render, you can use either the default Test Utilities or Enzyme, I personally find Enzyme's shallow render implementation much easier to work with.