Blog>
Snippets

Mocking Store State for Testing

Illustrates how to mock the TanStack Store's state for unit testing components that are tightly coupled with the store.
import { createStore } from 'tanstack-store-react';

// Original store setup
const useStore = createStore({
  initialState: {
    todos: []
  }
});
This code snippet shows the creation of a store using TanStack Store where the state includes a todos array. This setup is what we might use in the actual application.
const mockState = {
  todos: [
    { id: 1, text: 'Write unit tests', completed: false },
    { id: 2, text: 'Read documentation', completed: true }
  ]
};

useStore.setState(mockState);
Here, we define a mock state that represents a predefined state of the todos array. This mock state is then applied to the store using the `setState` function, effectively mocking the store's state for testing purposes.
import { render, screen } from '@testing-library/react';
import TodosComponent from './TodosComponent';

// Use this line in your test setup or directly in a test case
useStore.setState(mockState);

render(<TodosComponent />);
expect(screen.getByText('Write unit tests')).toBeInTheDocument();
expect(screen.getByText('Read documentation')).toBeInTheDocument();
Finally, this snippet demonstrates how to use the mocked store state in a unit test. We apply the mock state to the store, render the component (TodosComponent) that uses this store, and then use assertions to verify that the component behaves as expected based on the mocked state.