8. Testing Components Flashcards
What does testing React components mean?
- Verify output has not regressed
- Ensure that rarely occurring corner cases produce the correct output
- If component generates side effects, verify they occur but do not execute them
- Verify that user interactions are handled as expected
What are the factors that create variety across the spectrum of React components?
- Components may or may not have lifecycle handlers
- Components may or may not have internal state
- Components may or may not generate side effects
- Components may get state from arguments, or from external dependencies
What factors make a React component more testable?
- No internal state — output is an idempotent product of the props that are provided
- No side effects — any AJAX calls, UI changes, or other side effects are handled by sagas, thunks, etc., but not by components
- No lifecycle hooks — fetching data is handled on the application level, not the component level
What attributes of Redux make our React components more testable?
- Components don’t generate side-effects
- Components consist of logical display and container components
- Components do not have internal state
How should React Redux components be tested?
- Test Container and Display elements separately
- Use unit tests to verify methods and properties passed by Container are accurate
- Use snapshot tests to verify the output of the Display component, passing props directly
What in particular is Enzyme useful for testing as opposed to react-test-renderer?
A variety of interactions including click, keyboard, input, and more.
What makes Enzyme challenging to use?
The variety of open bugs.
What are the steps in testing stateful React components?
- Mock dependencies, then test them
- Use spies to verify side effects
- Move logic from lifecycle to services where possible
- Prevent regression with snapshots
- Inject values by writing mocks for services
- Make stateless components where possible
How do you use a mocked service rather than the original in your test?
By calling jest.mock
at the top of your test file and passing it the path to the original service — it then knows to look into the \_\_mocks\_\_
folder, find the mock, and use that rather than the original service.
eg. jest.mock("../../services/NotificationService");