In order to test LockScreen
, you must first understand what its Contract is. Understanding a component’s contract is the most important part of testing a React component. A contract defines the expected behavior of your component and what assumptions are reasonable to have about its usage. Without a clear contract, your component may be hard to understand. Writing tests is a great way to formally define your component’s contract.
Every React component has at least one thing that contributes to the definition of its contract:
- What it renders (which may be nothing)
Additionally, most component contracts are affected by these things as well:
- The props the component receives
- The state the component holds (if any)
- What the component does when the user interacts with it (via clicking, dragging, keyboard input, etc)
Some less common things that affect component contracts are:
- The context the component is rendered in
- What the component does when you call methods on its instance (public ref interface)
- Side effects that occur as part of the component lifecycle (componentDidMount, componentWillUnmount, etc
To find your component’s contract, ask yourself questions like:
- What does my component render?
- Does my component render different things under different circumstances?
- When I pass a function as a prop, what does my component use it for?Does it call it, or just give it to another component? If it calls it, what does it call it with?
- When the user interacts with my component, what happens?
I hope these methods will help you write your own React component tests. To summarize:
- Find your Component Contract first
- Decide which constraints are worth testing and which aren’t
- Prop types are not worth testing
- Inline styles are usually not worth testing
- The components you render and what props you give them are important to test
- Don’t test things that are not the concern of your component
Here are some things to consider:
- Does the component behave differently when it receives different values for a certain prop?
- Is a specific element rendered in the tree when the state changes to a certain value?
- What happens after the user performs some action? Are any external functions called? Do we expect the state to change?