Getting Started With React Cosmos

A Complete Guide to Component Isolation Testing

React development has evolved significantly, with component-based architectures becoming the standard for building modern web applications. As applications grow in complexity, so does the challenge of maintaining, testing, and iterating on individual components without the overhead of the entire application context.

React Cosmos is an open-source development tool that provides a dedicated sandbox for building, testing, and documenting React components in complete isolation. Unlike testing frameworks that focus on functional verification, React Cosmos emphasizes visual development, allowing developers to see their components render in real-time while having full control over the props, state, and context that influence their appearance.

The tool operates on a simple but powerful principle: components should be developed independently of the application they belong to. By creating isolated environments called fixtures, developers can render any component with any combination of props, explore different states visually, and verify that components behave correctly under various conditions--all without running the full application or writing traditional test code. Our web development services team regularly implements component isolation testing as part of comprehensive quality assurance workflows.

Why Use React Cosmos?

The adoption of React Cosmos brings numerous benefits to component development workflows.

Visual Test-Driven Development

React Cosmos enables Visual Test-Driven Development (Visual TDD), a methodology that combines the iterative development approach of TDD with immediate visual feedback. Developers can create fixtures that represent different component states, make changes to the component code, and immediately see how those changes affect the visual output.

Faster Feedback Loop

Component isolation through React Cosmos significantly reduces the feedback loop during development. Instead of navigating through an application to reach a specific component, developers can access any component directly through the Cosmos explorer. This accelerates development speed and makes it easier to catch visual regressions early in the development process.

Living Documentation

The tool also excels at documentation and design system maintenance. By creating comprehensive fixture libraries, teams automatically generate living documentation that shows how components should look and behave in different scenarios. New team members can explore the fixture library to understand component APIs and usage patterns without digging through application code.

Responsive Testing

Another significant advantage is the ability to test responsive designs within the same environment. React Cosmos allows developers to define custom viewports and test components across different screen sizes, ensuring that components adapt correctly to various devices without leaving the development server.

Key Features of React Cosmos

Everything you need for component development excellence

Component Isolation

Build and test components independently of your application context, eliminating the need to navigate through entire apps just to test a single component.

Visual Fixture Development

Create comprehensive fixture libraries that serve as both testing environments and living documentation for your component library.

Interactive Control Panel

Manipulate component props in real-time using useSelect and useValue hooks, enabling rapid exploration of component behavior across different scenarios.

Responsive Preview

Test components across different viewport sizes with built-in device simulation, ensuring consistent behavior across all screen sizes.

Multi-Bundler Support

Works seamlessly with Vite, Webpack, Next.js, Create React App, and React Native, making it adaptable to any modern React project.

Extensible Plugin System

Comprehensive plugin APIs allow customization of every aspect, from fixture loading to UI rendering, with an active community ecosystem.

Installation and Configuration

Prerequisites

Before installing React Cosmos, ensure that your development environment meets the minimum requirements. React Cosmos requires React version 16.8 or newer to take advantage of hooks and modern React patterns. Node.js version 10 or newer is required to run the Cosmos server and manage dependencies.

The installation process differs slightly depending on your project's build system. React Cosmos provides first-class integrations with Vite, Webpack, Create React App, Next.js, and React Native.

Basic Installation

For most projects, begin by installing React Cosmos as a development dependency:

npm install react-cosmos --save-dev
# or
yarn add react-cosmos -D

Create React App Configuration

For Create React App projects, create a cosmos.config.json file in your project's root directory:

{
 "staticPath": "public",
 "watchDirs": ["src"],
 "webpack": {
 "configPath": "react-scripts/config/webpack.config"
 },
 "globalImports": ["src/styles/main.css"]
}

Vite Configuration

Vite projects typically require less configuration:

{
 "staticPath": "public",
 "watchDirs": ["src"]
}

Adding Scripts

Add Cosmos scripts to your package.json:

{
 "scripts": {
 "cosmos": "cross-env FAST_REFRESH=false cosmos",
 "cosmos:export": "cross-env FAST_REFRESH=false cosmos-export"
 }
}

Start the development server with npm run cosmos or yarn cosmos. The server typically starts on port 5000, opening a web interface where you can browse fixtures and test components.

Core Concepts: Fixtures

Fixtures are the foundation of React Cosmos's component isolation system. A fixture is a file that exports a React component or React node for display in the Cosmos sandbox. Fixtures define how a component should be rendered for development and testing purposes.

Creating Basic Fixtures

A basic fixture imports a component and exports it as the default function:

import Button from '../components/Button/Button';

export default () => (
 <div className="w-60 mx-auto">
 <Button>Cosmos</Button>
 </div>
);

Multi-Fixtures

For component libraries, multi-fixtures export an object with named exports:

import FoodCard from '../components/FoodCard/FoodCard';
import CartCard from '../components/CartCard/CartCard';

export default {
 FoodCard: <FoodCard id={1} name="Test Item" price="9.99" />,
 CartCard: <CartCard id={1} name="Test Item" price="9.99" qty={1} />
};

Multi-fixtures appear as expandable entries in the Cosmos sidebar, allowing developers to navigate between related components without creating separate fixture files.

Fixture Organization

Fixtiles can be organized using either:

  • Files ending with .fixture.{js,jsx,ts,tsx} alongside components
  • A dedicated __fixtures__ directory within the source folder

Both approaches are automatically discovered by React Cosmos.

Control Panel: Props and State Manipulation

The control panel is one of React Cosmos's most powerful features, providing an interactive interface for manipulating component props in real-time.

useSelect Hook for Enumerated Props

The useSelect hook creates dropdown controls for props with predefined options:

import { useSelect } from 'react-cosmos/fixture';
import Button from '../components/Button/Button';

export default () => {
 const [variant] = useSelect('variant', {
 options: ['primary', 'secondary', 'outline'],
 });

 return <Button variant={variant}>Test Button</Button>;
};

useValue Hook for Numeric and String Props

For arbitrary values, the useValue hook creates input fields:

import { useValue } from 'react-cosmos/fixture';

export default () => {
 const [count] = useValue('count', { defaultValue: 0 });
 const [disabled] = useValue('disabled', { defaultValue: false });
 return <Counter count={count} disabled={disabled} />;
};

Combining Control Hooks

Real-world components often require multiple control hooks for comprehensive testing:

import { useSelect, useValue } from 'react-cosmos/fixture';

export default () => {
 const [variant] = useSelect('variant', {
 options: ['primary', 'secondary', 'outline'],
 });
 const [size] = useSelect('size', {
 options: ['small', 'medium', 'large'],
 });
 const [disabled] = useValue('disabled', { defaultValue: false });

 return (
 <Button variant={variant} size={size} disabled={disabled}>
 Test Button
 </Button>
 );
};

Decorators for Shared Configuration

Decorators provide a mechanism for wrapping fixtures with shared configuration, styles, or context providers.

Creating Decorators

Create a cosmos.decorator.js file in a fixture directory:

export default ({ children }) => (
 <div className="bg-gray-100 h-screen">
 {children}
 </div>
);

This decorator wraps all fixtures in the directory with a gray background and full viewport height.

Context Providers in Decorators

Decorators are ideal for providing React context that components need:

export default ({ children }) => (
 <ThemeProvider theme="light">
 <LocalizationProvider locale="en-US">
 {children}
 </LocalizationProvider>
 </ThemeProvider>
);

This allows components that depend on context to be tested in isolation without the overhead of setting up the entire application context. Multiple decorators can be composed to build complex environments incrementally.

Responsive Preview and Viewport Testing

React Cosmos includes a responsive preview feature for testing components across different screen sizes.

Configuring Device Viewports

Add viewport configurations to cosmos.config.json:

{
 "ui": {
 "responsivePreview": {
 "devices": [
 { "label": "iPhone 5", "width": 320, "height": 568 },
 { "label": "iPhone 6", "width": 375, "height": 667 },
 { "label": "iPhone 6 Plus", "width": 414, "height": 736 },
 { "label": "Medium", "width": 1024, "height": 768 },
 { "label": "Large", "width": 1440, "height": 900 }
 ]
 }
 }
}

Testing Responsive Components

When viewing a component, switch between devices using the viewport dropdown. The component renders within an iframe sized to the selected dimensions, accurately simulating how it will appear on that device.

This feature is particularly valuable for testing navigation components, grid layouts, and responsive forms that adapt their behavior based on available space. Combining component isolation testing with comprehensive end-to-end testing creates a robust testing strategy for React applications.

Best Practices for Component Development

Organizing Fixtures Effectively

A well-organized fixture structure makes component development more efficient. Consider organizing fixtures by component type--buttons, cards, forms, and layouts--creating separate directories for different categories.

Each fixture should represent a meaningful component state or usage scenario. For a Button component, meaningful fixtures might include primary-default, secondary-hover, disabled-state, and loading-state.

Naming Conventions

Use descriptive names for fixtures that clearly indicate the scenario being tested. Include comments when complex prop combinations require explanation. The Cosmos interface displays fixture names prominently, making descriptive naming essential for navigating large component libraries.

Integration with Testing Workflows

React Cosmos complements but does not replace traditional testing frameworks. Use Cosmos for visual development and exploratory testing, while maintaining unit and integration tests for functional verification. The combination provides comprehensive coverage.

Maintaining Fixture Quality

Keep fixtures up to date as components evolve. When component props change, update corresponding fixtures to reflect the new API. Regular fixture audits help identify obsolete fixtures that should be removed, keeping the library clean and navigable.

Conclusion

React Cosmos represents a significant advancement in React component development workflows, providing the isolation, visual feedback, and interactive controls that modern component development demands.

By enabling developers to build and test components independently of application context, Cosmos accelerates development cycles, improves component quality, and creates living documentation that evolves with the codebase. The tool's flexibility--supporting multiple bundlers, configuration options, and an extensible plugin system--makes it adaptable to diverse project requirements.

Getting started with React Cosmos involves installing the package, creating a configuration file, and beginning to build fixtures for existing components. The initial investment in fixture creation pays dividends throughout the development lifecycle, as components become easier to understand, test, and maintain.

For teams committed to component quality and development efficiency, React Cosmos is an essential addition to the React development toolkit. Our web development services team specializes in implementing component isolation testing and establishing development best practices that improve code quality and reduce maintenance overhead.

Frequently Asked Questions

Ready to Improve Your React Development Workflow?

Our team of React experts can help you implement component isolation testing and establish development best practices for your project.

Sources

  1. React Cosmos Official Documentation - Comprehensive guide covering fixtures, configuration, plugins, and architectural philosophy
  2. React Cosmos Fixtures Documentation - Core documentation on fixture modules, decorators, and fixture options
  3. React Cosmos Configuration Guide - cosmos.config.json setup and options
  4. LogRocket: Getting Started with React Cosmos - Practical tutorial with code examples showing fixture creation and visual TDD workflow
  5. OpenReplay: Getting Started with React Cosmos - Detailed walkthrough of component isolation testing and sandbox environment benefits