Software Engineer Encyclopedia
0%
Domain 07 · Frontend Engineering with Angular · Topic 7.7

Frontend Quality: Testing وAccessibility وPerformance وRelease

Frontend Quality — Testing, Accessibility and Performance

Component/unit/integration/E2E testing، Playwright، accessibility، visual regression، Core Web Vitals، bundle budgets، security review، error telemetry، CI quality gates وrelease checklist.

  • Intermediate
  • ~17 min read
  • 22 sections
  • 7 code examples
  • 1 diagrams
  • 5 questions
  • Priority L2 · Important
  • Angular 22 · Playwright · Web Vitals

المتطلبات قبل ما تبدأ

أساسيات البرمجة. الـ backend مش شرط لكن بيفيد في جزء الـ HTTP.

01

Frontend Quality: مش مجرد UI شكلها حلو

Correctness, usability, resilience and maintainability
Deep dive

Frontend quality تتكون من behavior correctness، accessibility، performance، security، resilience، maintainability و observability. UI جميلة لكنها ترسل payload غلط أو لا تعمل بالكيبورد أو تعرض بيانات user آخر ليست UI جيدة. اربط quality بالـ user journeys: login، search، create/update، pagination، error recovery و logout.

اختبارات frontend تكمل backend tests ولا تستبدلها. Unit tests تختبر pure logic، component tests تختبر rendering/interactions، service tests تختبر HTTP contract، E2E tests تختبر رحلة مستخدم كاملة. لا تجعل E2E هي الاختبار الوحيد لأنها أبطأ وأكثر هشاشة، ولا تعتمد على snapshots ضخمة لا تفهم semantics.

02

هرم اختبارات الـ frontend

Frontend test pyramid
Basics
E2EComponent (TestBed, harnesses)Unit: pure logic, services, interceptorsPlaywright: 5–10 flowsVitest + TestBedVitest, ms each
Many fast tests at the bottom, a few expensive end-to-end tests at the top
03

Unit و Component Testing في Angular

Test public behavior, not private implementation
Deep dive

اختبر component عبر DOM والـ user interactions: هل button disabled أثناء loading؟ هل validation message تظهر؟ هل empty state واضحة؟ لا تختبر private fields أو تفاصيل implementation التي قد تتغير مع refactor. استخدم Angular TestBed عند الحاجة للـ DI/template compilation، و mock services عند boundary. اختبر standalone imports وال pipes/directives في test environment.

TypeScriptComponent test behavior sketch
it('disables submit while the request is pending', () => {
  fixture.detectChanges();
  const button: HTMLButtonElement = fixture.nativeElement.querySelector('button[type=submit]');

  expect(button.disabled).toBeFalse();
  component.isSaving.set(true);
  fixture.detectChanges();
  expect(button.disabled).toBeTrue();
});

المثال يوضح الفكرة؛ APIs مثل signal access و fixture setup تعتمد على component implementation و Angular testing version. استخدم fakeAsync/tick أو async utilities حسب scheduler، ولا تخلط fake timers مع RxJS TestScheduler من غير فهم من يدير الوقت.

04

HTTP Service Testing و Contract Tests

Verify methods, URLs, payloads and error mapping
Deep dive

HttpTestingController يسمح باعتراض requests والتحقق من URL/method/headers/body ثم flush response أو error. اختبر 200، 204، 400/422 validation, 401/403, 409 conflict, 429, 5xx و network failure. تأكد أن service لا تسرب token إلى external URLs، وأن retry محدود ومناسب للـ method.

Contract tests بين frontend/backend مهمة عندما DTOs تتغير باستمرار. استخدم OpenAPI generation/check، schema compatibility checks، أو consumer-driven contracts عند تعقيد integration. Generated client لا يضمن أن backend deployment متوافق؛ اجعل CI يقارن schema ويفشل على breaking changes غير مقصودة.

05

E2E Testing باستخدام Playwright

Test critical user journeys in a real browser
Deep dive

Playwright يشغل browser حقيقي ويختبر navigation/forms/network. اكتب tests مستقرة باستخدام accessible roles/labels و test IDs عند الحاجة، لا تعتمد على CSS selectors هشة أو fixed sleeps. استخدم deterministic test data، isolated accounts، database reset strategy و mock external payment/email providers. لا تجعل E2E تضرب production أو ترسل رسائل حقيقية.

TypeScriptPlaywright: create an order flow sketch
import { test, expect } from '@playwright/test';

test('user can create an order', async ({ page }) => {
  await page.goto('/orders/new');
  await page.getByLabel('Customer email').fill('test@example.invalid');
  await page.getByLabel('Quantity').fill('2');
  await page.getByRole('button', { name: 'Create order' }).click();

  await expect(page.getByRole('status')).toContainText('Order created');
});

استخدم .invalid domain للاختبارات بدل إرسال بريد حقيقي. اختبر API failures و loading delays، وليس happy path فقط. Trace viewer و screenshots/videos تساعد debugging؛ تأكد من عدم حفظ secrets/PII في artifacts.

Playwright E2E: من Browser إلى API Contract

Playwright يختبر journey من منظور المستخدم: يفتح صفحة المنتجات، ينتظر loading، يبحث، يفتح التفاصيل، ويحفظ تعديلًا. استخدم API test environment أو seeded test database، ولا تستخدم production. إذا عملت mock للـ API فأنت تختبر UI behavior؛ وإذا اتصلت ببيئة integration فأنت تختبر integration أيضًا، لكن الاختبار يصبح أبطأ وأكثر حساسية للبيئة.

TypeScriptproducts.spec.ts
import { test, expect } from '@playwright/test';

test('user searches and edits a product', async ({ page }) => {
  await page.goto('/products');
  await expect(page.getByRole('heading', { name: 'Products' })).toBeVisible();

  await page.getByRole('searchbox', { name: 'Search products' }).fill('keyboard');
  await expect(page.getByRole('row', { name: /Keyboard/i })).toBeVisible();
  await page.getByRole('link', { name: /Keyboard/i }).click();

  await expect(page.getByRole('heading', { name: 'Product details' })).toBeVisible();
  await page.getByLabel('Product name').fill('Mechanical Keyboard');
  await page.getByRole('button', { name: 'Save changes' }).click();
  await expect(page.getByRole('status')).toContainText('saved');
});

لا تعتمد على waitForTimeout؛ انتظر assertion على UI أو response محدد. اجعل locator مبنيًا على role/label، واستخدم trace/video/screenshot عند الفشل. نفّذ الاختبارات بالتوازي فقط لو كل test يملك بيانات مستقلة. ضع cleanup واضحًا، واختبر authorization boundaries و keyboard flow و mobile viewport، ولا تخزن access tokens في trace artifacts.

06

Accessibility Audit: Keyboard و Screen Reader

Build for different interaction modes
Deep dive

ابدأ ب semantic HTML و labels و native controls. اختبر keyboard-only: Tab order، focus visibility، Enter/Space activation، Escape لل dialogs، focus trap/restore في modal. اختبر zoom/reflow و contrast و text resizing. ARIA يضيف semantics ولا يخلق behavior تلقائيًا. لا تستخدم aria-label لتغطية label مرئي مفقود من غير سبب.

Automated axe checks مفيدة لاكتشاف بعض violations، لكنها لا تحل محل manual screen-reader test. راجع headings hierarchy، landmarks، form error associations، live announcements، table headers، image alt، color-only status، motion preferences. Accessibility issue قد يكون blocker حتى لو visual QA نجح.

Accessibility Review: Keyboard و Screen Reader و Motion

اختبر الموقع بالكيبورد فقط: Tab/Shift+Tab، Enter/Space، Escape، arrow keys في widgets المناسبة، focus trap داخل dialogs، وإرجاع focus إلى trigger عند الإغلاق. استخدم headings و landmarks صحيحة، labels، accessible names، status messages، و error associations. لا تستخدم ARIA role غير مطابق لسلوك control.

راجع prefers-reduced-motion، contrast، zoom/reflow، text spacing، captions/transcripts للمحتوى السمعي، و RTL. automated axe checks تلتقط بعض المشاكل لكنها لا تختبر كل user journey؛ manual screen reader pass مهم للمكونات المعقدة. لا تعتبر accessibility “polish” بعد انتهاء التطوير؛ صممها مع component contract.

07

Visual Regression و Responsive QA

Catch unintended layout changes
Practical

Visual regression تقارن screenshots قبل/بعد التغيير. ثبّت viewport/browser/font/data/timezone حتى لا تظهر diffs عشوائية. لا تقبل كل diff تلقائيًا؛ راجع هل التغيير مقصود، وهل النص clipping أو RTL/layout broke. Screenshot test وحده لا يثبت accessibility أو behavior.

اختبر breakpoints التي تكسر layout بدل أسماء الأجهزة، مع 200% zoom، long translations، empty/loading/error states، dark mode، reduced motion و RTL. راقب sticky/fixed elements على mobile keyboard، touch target sizes و scroll containers.

08

Core Web Vitals و Performance Budgets

Measure user-perceived speed
Deep dive

Core Web Vitals تقيس user experience: LCP لتحميل المحتوى الرئيسي، INP لاستجابة التفاعل، CLS لاستقرار layout. thresholds تتغير عبر web.dev؛ راجع المصدر الحالي. قس field data من users و lab data من tests. لا تعتمد على Lighthouse score واحدة؛ device/network variability مهمة.

Performance budget يحدد حدودًا مثل initial JS bytes، route chunk size، LCP p75، API p95، image payload. راقب budget في CI حتى لا يتضخم bundle بصمت. استخدم lazy routes، image optimization، caching headers، compression، preconnect عند الحاجة، وتقليل expensive main-thread work. لا تضف preloading لكل شيء؛ ده قد يؤخر critical resources.

Performance Budget: Bundle و Core Web Vitals

راقب LCP لظهور المحتوى الرئيسي، INP لتفاعل المستخدم، CLS لاستقرار layout. Lighthouse lab data مفيدة للمقارنة لكنها ليست بديلًا عن field data. قلل JavaScript initial bundle، lazy-load routes، compress assets، cache static content، واحجز image dimensions لمنع layout shift. لا تؤخر critical CSS أو fonts بلا قياس.

Performance budget يجب يكون قابلًا للقياس في CI: bundle size thresholds، Lighthouse CI أو browser tests، و field monitoring بعد الإطلاق. لا تطارد score واحدًا على حساب accessibility أو correctness. اختبر low-end devices وشبكات بطيئة، لا desktop developer machine فقط.

09

Bundle Analysis و Rendering Performance

Find the real cost center
Practical

استخدم Angular build stats/bundle analyzer لمعرفة dependency التي ترفع initial bundle. Tree-shaking يحتاج imports قابلة للتحليل، و side-effectful packages قد تمنع إزالة code. Dynamic import يقسم chunk لكن لا يضمن أن chunk لن يحمل مبكرًا بسبب preloading. راقب duplicate dependencies والـ polyfills والـ locale data.

Large lists تحتاج pagination/virtual scrolling حسب UX. track keys تقلل DOM recreation. لا تعمل sorting/filtering O(n log n) داخل template expression لكل change detection؛ احسب derived state عبر computed أو service. لا تنفذ expensive synchronous parsing على main thread؛ استخدم Web Worker أو server-side processing إذا justified.

10

Frontend Security Review

The browser is an untrusted environment
Deep dive
  • لا تضع API secrets أو private keys أو DB connection strings في bundle.
  • لا تعتمد على hidden buttons/route guards لإقرار authorization؛ server checks كل request.
  • تجنب [innerHTML] مع user-controlled content، ولا تستخدم bypass sanitizer بلا threat review.
  • استخدم CSP مناسبة و Trusted Types عند compatibility، وراجع third-party scripts/dependencies.
  • احمِ cookie auth من CSRF حسب SameSite/anti-forgery strategy، وقلل XSS attack surface.
  • لا تسجل tokens/passwords/PII في console/telemetry/analytics.
  • راجع dependency advisories و lockfile و package provenance.

Frontend security ليست فقط XSS. تشمل supply chain، privacy، clickjacking/CSP، auth storage، CORS misunderstanding، open redirects، unsafe file preview/upload و sensitive data in browser storage.

Frontend Security: XSS و CSRF و Token Storage و Supply Chain

أي قيمة قادمة من user أو URL أو API تعامل معها كبيانات غير موثوقة. تجنب innerHTML أو bypassSecurityTrust* إلا مع sanitization وفهم دقيق؛ Angular sanitization لا يحمي كل custom DOM manipulation. لا تخزن access/refresh tokens في localStorage دون threat analysis؛ XSS يستطيع قراءتها. HttpOnly cookies تقلل سرقة cookie عبر JavaScript لكنها تحتاج CSRF defenses و SameSite/CORS configuration صحيحة.

لا تعتبر frontend route guard authorization. لا تضع API keys السرية أو cloud credentials في bundle. راجع dependencies و lockfile و npm audit/supply-chain alerts، وطبّق CSP و security headers من server/CDN، وراقب third-party scripts. اختبر open redirects و unsafe URL handling و postMessage origin validation.

Frontend Threat Model: XSS و CSRF و Token Storage

لا تضع access token طويل العمر في localStorage بلا threat analysis؛ أي XSS يستطيع قراءته. HttpOnly Secure SameSite cookies تقلل سرقة token عبر JavaScript لكنها تحتاج CSRF defenses عند إرسالها تلقائيًا. لا تستخدم bypassSecurityTrust... إلا بعد sanitization وفهم المصدر. لا تعرض untrusted HTML عبر innerHTML بلا sanitizer.

Frontend authorization مجرد UX؛ API يجب تتحقق من permissions لكل resource. لا تثق في hidden buttons أو route guards كحماية. تعامل مع URL/query parameters و postMessage و third-party scripts كمدخلات غير موثوقة. فعّل CSP مناسبة، وقلل script sources، ولا تسجل tokens أو PII في analytics/errors.

11

Error Monitoring و Release Observability

Connect UI failures to backend traces
Deep dive

اجمع frontend exceptions و failed navigation و API failures و web vitals، مع app version/environment/route و trace ID. اربط traceparent أو correlation ID بين Angular request و ASP.NET Core trace. لا ترسل request body أو query parameters sensitive. Sampling يقلل cost لكن حافظ على critical error signals.

Release marker مهم: لما error rate ترتفع بعد deployment، تحتاج تعرف أي version وصل لأي user. استخدم source maps بشكل آمن (private upload أو protected storage) ولا تنشر source maps publicly إذا تكشف source أو paths حساسة. Error grouping و release health تساعدك تقارن regressions.

12

Frontend CI Quality Gates

Automate the minimum release bar
Practical
  1. Install dependencies من lockfile بـ npm ci.
  2. Type-check/build production configuration.
  3. Run unit/component/service tests.
  4. Run lint/format and dependency audit.
  5. Run E2E critical paths على isolated test environment.
  6. Run accessibility smoke checks and bundle budget checks.
  7. Upload test reports/screenshots/trace artifacts مع sanitization.
  8. Deploy immutable artifact ثم smoke test و monitor release health.

لا تجعل flaky tests تتجاهل بلا نهاية. صنف failures: product bug، test bug، environment instability. كل quarantine لازم owner و expiry date. Quality gate جيد سريع، موثوق، ويمنع defect حقيقي بدل تعطيل delivery.

13

PWA و Offline UX

Offline behavior is a product decision
Practical

Progressive Web App يمكن أن توفر installability و service worker caching/offline behavior حسب browser/platform. لا cache كل API response بلا policy؛ user-specific data قد تظهر بعد logout أو على جهاز مشترك. Cache static assets versioned، وحدد stale-while-revalidate/network-first حسب resource. Offline write operations تحتاج queue/idempotency/conflict resolution، وليست مجرد localStorage.

اختبر update lifecycle: service worker قد يحتفظ بنسخة قديمة من app bundle بينما backend تغير contract. استخدم version compatibility و force-update UX عند الحاجة. لا تخزن payment secrets أو sensitive customer data offline إلا مع threat model و encryption/key lifecycle مناسب.

14

Frontend Release Checklist

Ready for real users
Practical
  • كل critical journey لها tests و error states.
  • Keyboard/screen-reader basics تم اختبارها يدويًا.
  • API contract و auth flow متوافقان مع backend.
  • Bundle budgets و Web Vitals مقاسة.
  • لا توجد secrets أو PII في bundle/logs.
  • Source maps/telemetry محمية و release version واضح.
  • Responsive/RTL/zoom/reduced-motion تم فحصها.
  • Rollback/feature flag plan موجود للتغييرات عالية المخاطر.

Frontend Release Checklist

قبل release راجع typecheck/lint/tests، accessibility keyboard pass، bundle budgets، CSP/security headers، API error handling، source maps/privacy، browser compatibility، mobile viewport، RTL، و real-user metrics. نفذ smoke test بعد deploy وتابع JavaScript error rate و Core Web Vitals. نجاح build وحده لا يثبت أن تجربة المستخدم سليمة.

15

اختبر فهمك

Knowledge check
Practical
لماذا E2E لا تكفي وحدها؟
لأنها أبطأ وهشة، ولا تغطي كل logic boundaries بكفاءة؛ نحتاج unit/component/service tests أيضًا.
هل automated accessibility scan يثبت أن الصفحة accessible؟
لا؛ يكتشف جزءًا من المشاكل ويجب استكماله باختبارات keyboard و screen reader.
ما الذي يقيسه INP؟
استجابة التفاعلات خلال زيارة المستخدم، وليس مجرد وقت تحميل أولي.
هل localStorage مناسب لحفظ secrets؟
لا؛ JavaScript وأي XSS يمكنه قراءة محتواه، ولا تحفظ فيه private credentials.
ما أهمية release marker في telemetry؟
يربط تدهور الأداء أو الأخطاء بإصدار محدد ويساعد rollback/investigation.
16

اختبارات Frontend: Unit و Component و Contract و E2E

Test behavior at the cheapest reliable layer
Deep dive

Unit tests تختبر pure functions و validators و state transitions. Component tests تختبر user-visible behavior: click، keyboard، loading/error/empty states. HTTP tests تتحقق من URL و headers و body و mapping. Contract tests تقارن API schema/client expectations. E2E تختبر critical user journey على browser حقيقي أو قريب منه، لكنها أبطأ وأكثر هشاشة.

لا تختبر تفاصيل implementation مثل عدد مرات استدعاء private method؛ اختبر ما يراه المستخدم. اجعل test data deterministic، واعزل الوقت والـ network، واستخدم stable selectors مثل role/name بدل CSS class. في Playwright انتظر condition أو locator state بدل sleep ثابت. عند فشل E2E احتفظ screenshot/trace/video بحسب الحاجة، ولا تعِد المحاولة لإخفاء flaky behavior.

Frontend Testing: Unit و Component و E2E

Unit tests للـ pure functions و validators و state reducers. Component tests تتحقق من rendered UI والتفاعل وال loading/error/empty states باستخدام DOM semantics. E2E تغطي journeys حرجة مثل login و checkout، لكنها قليلة نسبيًا لتقليل flakiness. اختبر accessibility عبر keyboard و role/name queries، وليس CSS selectors فقط.

لا تختبر implementation details مثل عدد مرات استدعاء private method إلا إذا كان ذلك contract. استخدم mock للـ HTTP boundary، لكن احتفظ ببعض integration tests مع API contract الحقيقي. ثبّت test data و clock، وانتظر observable UI state بدل sleeps ثابتة. اجعل screenshots/visual tests مكملة وليست بديلًا عن assertions وظيفية.

17

Frontend Quality Gates: Lint و Typecheck و A11y و Bundle

Make quality repeatable in pull requests
Deep dive

CI frontend يجب تشغل formatter/linter، TypeScript typecheck، unit/component tests، production build، bundle budget، accessibility automated scan، وربما E2E smoke tests. افصل flaky E2E suite عن fast PR gate إذا كانت بطيئة، لكن لا تسمح أن تصبح غير مشغلة أبدًا. ثبت Node/package manager versions، lockfile، و dependency updates policy.

راجع third-party packages و scripts و CSP، وافحص dependency vulnerabilities مع تقييم exploitability. اجعل preview deployment لكل PR عند الحاجة لتسهيل visual review. بعد release راقب real-user metrics و JavaScript errors و API failures مع redaction؛ لا ترسل user content أو tokens إلى telemetry.

18

Frontend Error Monitoring و Privacy

Capture useful failures without collecting sensitive data
Practical

اجمع JavaScript errors و unhandled promise rejections و failed API requests مع release version و route template و correlation ID. لا ترسل access tokens أو form contents أو raw query strings الحساسة. source maps تساعد على stack traces مفهومة، لكن لا تنشرها public بلا قرار؛ ارفعها إلى monitoring provider بصلاحيات مناسبة.

اجعل user-facing error message واضحة وقابلة للتصرف، مع retry فقط للعمليات الآمنة أو idempotent. سجّل technical detail داخليًا بعد redaction. راقب error rate بعد deployment وقارنها بالنسخة السابقة، وحدد alert thresholds لا تسبب ضوضاء من browser extensions أو أخطاء غير قابلة للتحكم.

19

E2E Test عملي بـ Playwright

Assert user-visible behavior, not implementation details
Practical
TypeScriptPlaywright test for a critical checkout journey
import { test, expect } from '@playwright/test';

test('customer can review an order before placing it', async ({ page }) => {
  await page.goto('/cart');
  await page.getByRole('button', { name: 'Continue to checkout' }).click();
  await expect(page.getByRole('heading', { name: 'Review order' })).toBeVisible();
  await expect(page.getByTestId('order-total')).not.toHaveText('');
  await expect(page.getByRole('button', { name: 'Place order' })).toBeEnabled();
});

هذا test يتحقق من user-visible contract؛ لا ينفذ payment حقيقيًا. استخدم seeded test data أو mocked sandbox boundary، وامنع side effects مالية. لا تعتمد على arbitrary sleeps؛ استخدم auto-waiting locators. اختبر mobile viewport و keyboard/accessibility journeys أيضًا، واحتفظ بـ trace/video عند failure لتسهيل diagnosis.

20

Pipeline عملي: Angular Quality Gates

Reproducible checks before every merge
Deep dive

الـ quality gate مش مجرد تشغيل ng build. افصل checks سريعة على كل Pull Request عن checks أبطأ قبل release. المثال يفترض scripts موجودة في package.json؛ عدّل الأسماء حسب workspace عندك وثبّت Node والـ lockfile.

YAML.github/workflows/frontend-ci.yml
name: frontend-ci
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
concurrency:
  group: frontend-${{ github.ref }}
  cancel-in-progress: true
jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint --if-present
      - run: npm run typecheck --if-present
      - run: npm test -- --watch=false
      - run: npm run build -- --configuration production
      - uses: actions/upload-artifact@v4
        if: success()
        with:
          name: frontend-dist
          path: dist/
          if-no-files-found: error
          retention-days: 7

npm ci يثبت اعتمادًا على lockfile ولا يحدّث dependencies بصمت. الـ PR job لا يحتاج cloud credentials أو write permissions. لا تعرض production secrets على workflow ينفذ كودًا من forks. أضف Playwright في job منفصل على preview أو local test server، وارفع trace عند الفشل مع retention محدود.

اجعل deploy job محميًا بـ Environment approval، وانشر artifact immutable، ثم نفّذ smoke test. أضف accessibility smoke و bundle budget و dependency audit حسب المخاطر. نجاح lint و unit tests و build لا يثبت وحده أن keyboard journey أو API integration سليمة.

21

اختبارات API و Component بشكل ثابت

Deterministic fixtures, loading states and failure paths
Practical

اختبارات الواجهة تصبح flaky بسبب shared test data أو fixed sleeps أو selectors مرتبطة بتفاصيل CSS. جهّز بيانات مستقلة لكل test، واستخدم semantic locators، وتحكم في HTTP boundary. لكل شاشة تعتمد على API اختبر loading و success/empty و failure/retry.

TypeScriptPlaywright: mock API and assert empty state
import { test, expect } from '@playwright/test';

test('shows an empty state when there are no products', async ({ page }) => {
  await page.route('**/api/products**', async route => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify({ items: [], totalCount: 0, page: 1 })
    });
  });
  await page.goto('/products');
  await expect(page.getByRole('heading', { name: 'Products' })).toBeVisible();
  await expect(page.getByRole('status')).toContainText('No products yet');
  await expect(page.getByRole('progressbar')).toHaveCount(0);
});

هذا يعزل frontend عن backend لكنه لا يثبت أن API الحقيقية ترجع نفس الـ shape؛ لذلك أضف contract/integration test. اختبر 401 و403 و409 و429 و5xx وانقطاع الشبكة. لا تعِد إرسال POST غير idempotent تلقائيًا؛ قد تنشئ الطلب مرتين. واستخدم test accounts وبيانات معزولة بدل مشاركة state بين الاختبارات.

22

Angular HTTP Integration Test بـ HttpTestingController

Verify request contracts, headers and failure mapping
Practical

اختبار الـ service باستخدام HttpTestingController يثبت إن Angular أرسل method و URL و body والـ headers المتوقعة، وإن الكود تعامل مع response أو failure بشكل صحيح. لا تستخدم backend حقيقي في unit/integration test الخاص بالـ HTTP client؛ اعزل الشبكة وخلّي test هو الذي يرد بالـ fixture. تأكد من استدعاء verify() بعد كل test حتى لا تترك requests معلقة.

TypeScriptproducts-api.spec.ts
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
import { ProductsApi } from './products-api';

describe('ProductsApi', () => {
  let api: ProductsApi;
  let http: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(), provideHttpClientTesting()]
    });
    api = TestBed.inject(ProductsApi);
    http = TestBed.inject(HttpTestingController);
  });

  afterEach(() => http.verify());

  it('requests a paged product list', () => {
    let result: unknown;
    api.list({ page: 2, pageSize: 20 }).subscribe(value => result = value);

    const request = http.expectOne(req =>
      req.url === '/api/products' && req.params.get('page') === '2' && req.params.get('pageSize') === '20'
    );
    expect(request.request.method).toBe('GET');
    request.flush({ items: [{ id: 'p-1', name: 'Keyboard' }], totalCount: 1 });
    expect(result).toEqual({ items: [{ id: 'p-1', name: 'Keyboard' }], totalCount: 1 });
  });

  it('surfaces a not-found response for a missing product', () => {
    let status = 0;
    api.getById(42).subscribe({
      error: error => status = error.status
    });
    const request = http.expectOne('/api/products/42');
    expect(request.request.method).toBe('GET');
    request.flush({ title: 'Not found' }, { status: 404, statusText: 'Not Found' });
    expect(status).toBe(404);
  });
});

ترتيب providers مهم: provideHttpClient() أولًا ثم provideHttpClientTesting() حتى يستبدل testing backend الـ real backend. أضف tests لـ401/403/422/429/500، timeout/network error، query encoding، auth header policy، وعدم تسريب secrets. اختبر interceptor منفصلًا أو ضمن service test بحسب contract؛ لا تجعل test يعتمد على implementation details غير مهمة.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 14 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionUnit and Component Testing§01
New sectionAccessibility (ARIA, keyboard)§01
New sectionResponsive Design§01
New sectionBrowser Rendering and DOM§01
SuggestedUnit and Component Testing§01
SuggestedAccessibility (ARIA, keyboard)§01
SuggestedResponsive Design§01
SuggestedBrowser Rendering and DOM§01
SuggestedE2E Testing (Playwright)§01
SuggestedCore Web Vitals (LCP, INP, CLS)§01
SuggestedBundle Size and Lazy Loading§01
SuggestedError Monitoring§01
SuggestedVisual Regression§01
SuggestedPWA§01

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس