乐闻世界logo
搜索文章和话题

How to perform unit and integration testing in SolidJS? What testing tools are recommended?

2月21日 15:23

SolidJS provides powerful testing tools and methods to test components and reactive logic:

Testing Tools:

javascript
import { render, screen, fireEvent, waitFor } from '@solidjs/testing-library'; import { describe, it, expect } from 'vitest'; describe('Counter Component', () => { it('renders initial count', () => { render(() => <Counter />); expect(screen.getByText('Count: 0')).toBeInTheDocument(); }); it('increments count when button clicked', async () => { render(() => <Counter />); const button = screen.getByText('+'); fireEvent.click(button); await waitFor(() => { expect(screen.getByText('Count: 1')).toBeInTheDocument(); }); }); });

Testing Reactive Logic:

javascript
import { createSignal, createEffect } from 'solid-js'; import { createRoot } from 'solid-js'; describe('Reactive Logic', () => { it('tracks signal changes', () => { createRoot((dispose) => { const [count, setCount] = createSignal(0); let effectCallCount = 0; createEffect(() => { effectCallCount++; count(); }); expect(effectCallCount).toBe(1); setCount(1); expect(effectCallCount).toBe(2); dispose(); }); }); });

Testing Async Operations:

javascript
import { createResource } from 'solid-js'; describe('Async Operations', () => { it('handles loading state', async () => { const fetchMock = vi.fn(() => new Promise(resolve => setTimeout(() => resolve({ data: 'test' }), 100)) ); const [data] = createResource(fetchMock); expect(data.loading).toBe(true); await waitFor(() => expect(data.loading).toBe(false)); expect(data()).toEqual({ data: 'test' }); }); });

Testing User Interactions:

javascript
describe('User Interactions', () => { it('handles form submission', () => { render(() => <LoginForm />); const input = screen.getByLabelText('Email'); const button = screen.getByText('Submit'); fireEvent.input(input, { target: { value: 'test@example.com' } }); fireEvent.click(button); expect(screen.getByText('Submitted: test@example.com')).toBeInTheDocument(); }); });

Testing Routing:

javascript
import { Router } from '@solidjs/router'; describe('Routing', () => { it('renders correct component for route', () => { render(() => ( <Router> <Routes> <Route path="/" component={Home} /> <Route path="/about" component={About} /> </Routes> </Router> )); expect(screen.getByText('Home Page')).toBeInTheDocument(); }); });

Best Practices:

  • Use @solidjs/testing-library for component testing
  • Wrap tests with createRoot for automatic cleanup
  • Test user behavior, not implementation details
  • Use waitFor for async operations
  • Mock external dependencies and API calls
  • Keep tests independent and repeatable
标签:SolidJS