0
votes

Say I have a simple React functional component that largely just observes changes in context and renders some view of the state from the context.

export default function Observer(props) {
  // I have a separate dispatch context for performance. This component doesn't dispatch
  const state = useContext(SomeContext);
  
  return (
    <div>Foo is now {state.foo}</div>
  )
}

For testing under jest/react testing library, I was imagining a few possibilities:

  1. Wire up a wrapper for the context that just instantiates different states for each test. This seems like it would be easy and straightforward. Is this the typical pattern?
  2. Instantiate each test with real initial state. Then somehow change state and expect the component to update. Perhaps using dispatch from the test code somehow. Most examples I see fire events, but this component doesn't dispatch anything, it just observes.
  3. Render a larger part of the app, with other components that update the state. This seems like a bad choice for a unit test of a small, simple component.