10.9 - Lighthouse - הרצאה
לייטהאוס ואסטרטגיית בדיקות - Lighthouse and Testing Strategy¶
בשיעור זה נלמד להשתמש ב-Lighthouse לביקורת מקיפה של אתרים, וכיצד לבנות אסטרטגיית בדיקות יעילה לפרויקט אמיתי.
מה זה לייטהאוס - Lighthouse¶
- כלי אוטומטי בקוד פתוח מבית Google
- מבצע ביקורת מקיפה של דפי אינטרנט
- בודק חמישה תחומים: ביצועים, נגישות, שיטות עבודה מומלצות, SEO, ו-PWA
- מחזיר ציון 0-100 לכל תחום עם המלצות ספציפיות לשיפור
ביקורות לייטהאוס - Lighthouse Audits¶
ביצועים - Performance¶
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- Total Blocking Time (TBT)
- Cumulative Layout Shift (CLS)
- Speed Index
- בדיקות נוספות: גודל תמונות, JavaScript לא בשימוש, CSS לא בשימוש, זמן תגובת שרת
נגישות - Accessibility¶
- ניגודיות צבעים מספקת
- alt text לתמונות
- labels לאלמנטי טופס
- שימוש נכון ב-ARIA
- מבנה כותרות הגיוני (H1-H6)
- ניווט עם מקלדת
- הtag lang ב-HTML
שיטות עבודה מומלצות - Best Practices¶
- שימוש ב-HTTPS
- אין שגיאות JavaScript בקונסול
- תמונות ברזולוציה מתאימה
- אין API-ים מיושנים
- כותרות אבטחה מוגדרות
SEO¶
- מטא-tags קיימות (title, description)
- הtag viewport
- קישורים עם טקסט תיאורי
- דף ניתן לסריקה (לא חסום ב-robots.txt)
- מבנה HTML סמנטי
הרצת לייטהאוס¶
מ-Chrome DevTools¶
1. Open DevTools (F12)
2. Go to the Lighthouse tab
3. Choose the categories you want to check
4. Choose device: Mobile or Desktop
5. Click "Analyze page load"
מ-CLI¶
# global installation
npm install -g lighthouse
# basic run
lighthouse https://example.com
# run with settings
lighthouse https://example.com \
--output html \
--output-path ./reports/report.html \
--view
# check specific categories
lighthouse https://example.com \
--only-categories=performance,seo
# run with a preset
lighthouse https://example.com --preset=desktop
# JSON format
lighthouse https://example.com \
--output json \
--output-path ./reports/report.json
בדיקות אוטומטיות ב-CI¶
// lighthouserc.json
{
"ci": {
"collect": {
"url": ["http://localhost:3000/", "http://localhost:3000/about"],
"numberOfRuns": 3,
"startServerCommand": "npm run start"
},
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.9 }],
"categories:accessibility": ["error", { "minScore": 0.9 }],
"categories:best-practices": ["warn", { "minScore": 0.9 }],
"categories:seo": ["error", { "minScore": 0.9 }]
}
},
"upload": {
"target": "temporary-public-storage"
}
}
}
# .github/workflows/lighthouse.yml
name: Lighthouse CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
- name: Run Lighthouse CI
run: |
npm install -g @lhci/cli
lhci autorun
פרשנות ציוני לייטהאוס¶
איך לקרוא את הדוח¶
- ציון 90-100: ירוק - מצוין
- ציון 50-89: כתום - צריך שיפור
- ציון 0-49: אדום - דורש תיקון דחוף
טיפים לשיפור ציונים¶
// 1. performance - the things that matter most:
// - image optimization (WebP, lazy loading, sizes)
// - reduce JavaScript (code splitting, tree shaking)
// - optimized fonts (next/font)
// - SSR / SSG
// 2. accessibility - common checks:
// alt text for every image
<img src="photo.jpg" alt="תיאור התמונה" />
// label for every input
<label htmlFor="email">אימייל</label>
<input id="email" type="email" />
// color contrast - minimum 4.5:1
// use the tool: https://webaim.org/resources/contrastchecker/
// lang attribute
<html lang="he" dir="rtl">
// 3. SEO - basic checks:
<title>כותרת ייחודית ותיאורית</title>
<meta name="description" content="תיאור הדף בעד 155 תווים" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
אסטרטגיית בדיקות לפרויקט אמיתי¶
מה לבדוק בכל רמה¶
Unit tests (70% of tests):
- utility functions (validation, formatting, calculations)
- custom hooks
- business logic (state machines, reducers)
- helper functions
Integration tests (20% of tests):
- main React components
- forms with validation
- components that depend on an API
- complex user interactions
E2E tests (10% of tests):
- registration/login flow
- purchase flow
- main navigation
- business-critical flows
דוגמה לאפליקציית חנות¶
Unit tests:
├── utils/
│ ├── formatPrice.test.ts
│ ├── validateForm.test.ts
│ ├── calculateDiscount.test.ts
│ └── filterProducts.test.ts
├── hooks/
│ ├── useCart.test.ts
│ ├── useAuth.test.ts
│ └── usePagination.test.ts
Integration tests:
├── components/
│ ├── ProductCard.test.tsx
│ ├── CartSummary.test.tsx
│ ├── CheckoutForm.test.tsx
│ ├── SearchBar.test.tsx
│ └── ProductFilters.test.tsx
E2E tests:
├── e2e/
│ ├── purchase-flow.spec.ts
│ ├── auth.spec.ts
│ └── product-search.spec.ts
יעדי כיסוי ובדיקות פרגמטיות - Coverage Goals¶
כיסוי קוד - Code Coverage¶
// vite.config.ts - coverage configuration
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
include: ['src/**/*.{ts,tsx}'],
exclude: [
'src/**/*.test.{ts,tsx}',
'src/**/*.spec.{ts,tsx}',
'src/test/**',
'src/**/*.d.ts',
],
thresholds: {
statements: 80,
branches: 75,
functions: 80,
lines: 80,
},
},
},
});
יעדים פרגמטיים¶
- אין צורך ב-100% coverage - זה לא ריאלי ולא יעיל
- יעד טוב: 80% statements, 75% branches
- תעדפו כיסוי של קוד קריטי על פני כיסוי של כל שורה
- בדקו את מה שיכול להישבר, לא את מה שברור שעובד
What's worth testing:
- critical business logic
- main user interactions
- edge cases and errors
- code that changes frequently
What's less important to test:
- simple UI components that just display props
- third-party library code
- configuration files
- TypeScript types
בדיקות רציפות ב-CI/CD - Continuous Testing¶
הגדרת CI עם בדיקות¶
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run lint
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npx vitest run --coverage
- name: Upload coverage
uses: actions/upload-artifact@v4
with:
name: coverage
path: coverage/
e2e-tests:
runs-on: ubuntu-latest
needs: [lint, unit-tests]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npx playwright install --with-deps
- run: npm run build
- run: npx playwright test
- name: Upload report
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/
lighthouse:
runs-on: ubuntu-latest
needs: [unit-tests]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm install -g @lhci/cli
- run: lhci autorun
סדר בדיקות ב-CI¶
1. Lint + Type Check (fast - 30 seconds)
↓
2. Unit tests (fast - 1-2 minutes)
↓
3. Integration tests (medium - 2-3 minutes)
↓
4. Build (medium - 1-2 minutes)
↓
5. E2E tests (slow - 3-5 minutes)
↓
6. Lighthouse (medium - 2-3 minutes)
- בדיקות מהירות רצות קודם - אם נכשלות, אין טעם להמשיך
- בדיקות E2E רצות רק אחרי שהבדיקות המהירות עברו
- Lighthouse רץ על ה-build המוגמר
תבנית לבדיקות חדשות¶
// unit test template
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { functionUnderTest } from './module';
describe('functionUnderTest', () => {
// Arrange - setup shared by all the tests
beforeEach(() => {
vi.restoreAllMocks();
});
it('should handle the happy path', () => {
// Arrange
const input = 'valid input';
// Act
const result = functionUnderTest(input);
// Assert
expect(result).toBe('expected output');
});
it('should handle edge case', () => {
// Arrange, Act, Assert
});
it('should throw on invalid input', () => {
expect(() => functionUnderTest(null)).toThrow();
});
});
// component test template
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import { ComponentUnderTest } from './Component';
describe('ComponentUnderTest', () => {
const defaultProps = {
// default props
};
it('should render correctly', () => {
render(<ComponentUnderTest {...defaultProps} />);
// render checks
});
it('should handle user interaction', async () => {
const user = userEvent.setup();
render(<ComponentUnderTest {...defaultProps} />);
await user.click(screen.getByRole('button'));
// checks after interaction
});
});
סיכום¶
- Lighthouse מבצע ביקורת מקיפה: ביצועים, נגישות, Best Practices, SEO
- ניתן להריץ מ-DevTools, CLI, או CI
- יעד: ציון 90+ בכל הקטגוריות
- אסטרטגיית בדיקות: 70% יחידה, 20% אינטגרציה, 10% E2E
- כיסוי קוד: יעד 80% - לא 100%
- בדקו את מה שקריטי ומה שיכול להישבר
- CI/CD: הריצו בדיקות מהירות קודם, E2E אחרון
- Lighthouse ב-CI מבטיח שביצועים ונגישות לא ייפגעו