Ted P
Ted P

Reputation: 95

Testing React component that observes state

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.

Upvotes: 0

Views: 1642

Answers (1)

Emmanuel Ponnudurai
Emmanuel Ponnudurai

Reputation: 1074

The first option is the way to go. As you already mentioned, the component in question is a consumer of the context. So, if it is provided with some value for context, it will most certainly use it.

You can create a simple function to pass different context values, which is provided via provider and is rendered. Then you assert what happens,


const renderComponent = (contextValue) => {
  render(
    <SomeContextProvider value={contextValue}>
      <Observer />
    </SomeContextProvider>
  );
};

test('my test case name', () => {
  render({foo: abc});
  expect(screen.getByText('Foo is now abc')).toBeInTheDocument();
})

Some good reading here https://testing-library.com/docs/example-react-context/

Upvotes: 1

Related Questions