@schalkneethling/calavera-skill-frontend-testing 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Schalk Neethling
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ {
2
+ "$schema": "https://calavera.schalkneethling.com/schemas/calavera-artifact.schema.json",
3
+ "schemaVersion": 1,
4
+ "id": "skill-frontend-testing",
5
+ "type": "skill",
6
+ "displayName": "Frontend testing",
7
+ "payload": "payload/frontend-testing",
8
+ "compatibility": {
9
+ "calavera": ">=2.2.0 <3"
10
+ }
11
+ }
package/package.json ADDED
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@schalkneethling/calavera-skill-frontend-testing",
3
+ "version": "0.2.0-next.1",
4
+ "description": "Frontend testing artifact for Calavera.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+ssh://git@github.com/schalkneethling/create-project-calavera.git",
9
+ "directory": "packages/artifacts/skill-frontend-testing"
10
+ },
11
+ "files": [
12
+ "calavera-artifact.json",
13
+ "payload"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ ".": "./calavera-artifact.json",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public",
22
+ "provenance": true
23
+ }
24
+ }
@@ -0,0 +1,348 @@
1
+ ---
2
+ name: frontend-testing
3
+ description: Write tests that start with acceptance criteria, then add implementation tests for robustness. Use when writing unit tests (Vitest), end-to-end tests (Playwright), visual regression tests, or accessibility tests. Emphasizes user-centric testing, semantic locators, accessibility validation, and the balance between acceptance and implementation testing.
4
+ ---
5
+
6
+ # Frontend Testing
7
+
8
+ Start by writing tests that validate acceptance criteria. Then add implementation tests where they provide value.
9
+
10
+ ## Core Principle
11
+
12
+ > "The more your tests resemble the way your software is used, the more confidence they can give you." — Kent C. Dodds
13
+
14
+ This principle guides testing decisions, but isn't the whole picture:
15
+
16
+ - **Acceptance criteria tests** verify the system does what users/stakeholders need. These should be stable across refactors.
17
+ - **Implementation tests** verify the pieces are robust — edge cases, error handling, complex logic. These may change when you refactor.
18
+
19
+ Both have value. The anti-pattern to avoid is tests that _only_ mirror implementation without validating meaningful behavior.
20
+
21
+ ## When to Load References
22
+
23
+ Load reference files based on test type:
24
+
25
+ - **Unit tests with DOM**: `references/locator-strategies.md`
26
+ - **E2E tests**: `references/locator-strategies.md`, `references/aria-snapshots.md`
27
+ - **Visual regression tests**: `references/visual-regression.md`
28
+ - **Accessibility audits**: `references/accessibility-testing.md`
29
+ - **Structure validation**: `references/aria-snapshots.md` — consolidate multiple assertions into one
30
+ - **All tests**: Start with this file for core workflow
31
+
32
+ ## Workflow
33
+
34
+ ### Step 1: Start with Acceptance Criteria
35
+
36
+ Before writing any test, identify what the code should do from the user's perspective.
37
+
38
+ Ask for or extract criteria from:
39
+
40
+ - Ticket description or user story
41
+ - Figma annotations
42
+ - Functional requirements
43
+ - Product owner clarification
44
+
45
+ Document criteria as a checklist. These become your first tests.
46
+
47
+ **Write acceptance tests before reading implementation.** This prevents circular validation where tests just confirm "code does what code does."
48
+
49
+ ### Step 2: Map Criteria to Test Cases
50
+
51
+ For each criterion, identify:
52
+
53
+ - **Happy path**: Normal expected behavior
54
+ - **Edge cases**: Boundary conditions
55
+ - **Error cases**: Invalid inputs, failures
56
+
57
+ Example mapping:
58
+
59
+ ```text
60
+ Criterion: "User can filter products by category"
61
+ ├─ Happy path: Select category, products filter correctly
62
+ ├─ Edge case: No products match filter, show empty state
63
+ ├─ Edge case: Clear filter, all products show again
64
+ ├─ Error case: Filter API fails, show error message
65
+ └─ Accessibility: Filter controls are keyboard accessible
66
+ ```
67
+
68
+ ### Step 3: Add Implementation Tests (Unit Tests)
69
+
70
+ After acceptance tests pass, add unit tests for implementation robustness:
71
+
72
+ - **Edge cases** the criteria don't cover (null, undefined, empty arrays, boundary values)
73
+ - **Algorithm correctness** for complex calculations
74
+ - **Error handling paths** (exceptions, network failures, parse errors)
75
+ - **Complex branching logic** hard to exercise through integration tests
76
+ - **Performance-sensitive code** that needs specific validation
77
+
78
+ ```text
79
+ Function: filterProducts(products, category)
80
+ ├─ Acceptance: Returns matching products (from criteria)
81
+ ├─ Implementation: Returns empty array when products is null
82
+ ├─ Implementation: Returns all products when category is empty string
83
+ ├─ Implementation: Handles case-insensitive category matching
84
+ └─ Implementation: Does not mutate original array
85
+ ```
86
+
87
+ The distinction: acceptance tests should rarely change on refactor; implementation tests may need updates when internals change.
88
+
89
+ ### Step 4: Choose Test Type
90
+
91
+ | Scenario | Test Type | Tool |
92
+ | ----------------------------- | ------------------ | -------------------------------- |
93
+ | Pure logic (no DOM) | Unit test | Vitest |
94
+ | Component behavior | Unit test with DOM | Vitest + Testing Library |
95
+ | User flows, real browser | E2E test | Playwright |
96
+ | Semantic structure validation | ARIA snapshot | Playwright `toMatchAriaSnapshot` |
97
+ | Visual appearance | VRT | Playwright screenshots |
98
+ | Accessibility compliance | A11y test | Playwright + axe-core |
99
+
100
+ **ARIA snapshots** are particularly valuable for E2E tests. A single snapshot can replace multiple individual assertions while validating the accessibility tree structure.
101
+
102
+ **DOM Environment for Unit Tests:** Prefer happy-dom over jsdom. It's faster, and its API limitations serve as a useful signal — if happy-dom doesn't support what you're testing, consider whether it belongs in an E2E test instead.
103
+
104
+ ### Step 5: Write Tests Before/Alongside Code
105
+
106
+ - **Ideal**: Write test first, then implementation (TDD)
107
+ - **Acceptable**: Write test immediately after implementing each criterion
108
+ - **Avoid**: Write all tests after implementation is "done"
109
+
110
+ ## Test Structure
111
+
112
+ ### Unit Tests (Vitest)
113
+
114
+ ```javascript
115
+ describe("calculateDiscount", () => {
116
+ describe("when customer has premium membership", () => {
117
+ it("applies 20% discount to order total", () => {
118
+ // Arrange - Set up test data matching criterion
119
+ const order = { total: 100, membership: "premium" };
120
+
121
+ // Act - Call the function
122
+ const result = calculateDiscount(order);
123
+
124
+ // Assert - Verify expected outcome from requirements
125
+ expect(result).toBe(80);
126
+ });
127
+ });
128
+ });
129
+ ```
130
+
131
+ ### Component Tests (Vitest + Testing Library)
132
+
133
+ ```javascript
134
+ import { render, screen } from "@testing-library/react";
135
+ import userEvent from "@testing-library/user-event";
136
+
137
+ describe("LoginForm", () => {
138
+ describe("when credentials are invalid", () => {
139
+ it("displays error message to user", async () => {
140
+ const user = userEvent.setup();
141
+ render(<LoginForm />);
142
+
143
+ // Interact using accessible queries
144
+ await user.type(screen.getByLabelText(/email/i), "invalid@test.com");
145
+ await user.type(screen.getByLabelText(/password/i), "wrong");
146
+ await user.click(screen.getByRole("button", { name: /sign in/i }));
147
+
148
+ // Assert on user-visible outcome
149
+ expect(await screen.findByRole("alert")).toHaveTextContent(/invalid credentials/i);
150
+ });
151
+ });
152
+ });
153
+ ```
154
+
155
+ ### E2E Tests (Playwright)
156
+
157
+ ```javascript
158
+ import { test, expect } from "@playwright/test";
159
+
160
+ test.describe("Product Catalog", () => {
161
+ test.describe("filtering by category", () => {
162
+ test("shows only matching products", async ({ page }) => {
163
+ await page.goto("/products");
164
+
165
+ // Use semantic locators
166
+ await page.getByRole("combobox", { name: /category/i }).selectOption("Electronics");
167
+
168
+ // Assert count, then spot-check first/last
169
+ const products = page.getByRole("article");
170
+ await expect(products).toHaveCount(5);
171
+ await expect(products.first()).toContainText(/electronics/i);
172
+ await expect(products.last()).toContainText(/electronics/i);
173
+ });
174
+ });
175
+ });
176
+ ```
177
+
178
+ When you need to verify all items, use `Promise.all` for parallel assertions:
179
+
180
+ ```javascript
181
+ test("all products match filter", async ({ page }) => {
182
+ await page.goto("/products");
183
+ await page.getByRole("combobox", { name: /category/i }).selectOption("Electronics");
184
+
185
+ const products = await page.getByRole("article").all();
186
+
187
+ // Parallel assertions — faster than sequential await in a loop
188
+ await Promise.all(
189
+ products.map((product) => expect(product.getByText(/electronics/i)).toBeVisible()),
190
+ );
191
+ });
192
+ ```
193
+
194
+ ### E2E Tests with ARIA Snapshots
195
+
196
+ ARIA snapshots consolidate multiple assertions into one, validating semantic structure:
197
+
198
+ ```javascript
199
+ test.describe("Login Page", () => {
200
+ test("has correct form structure", async ({ page }) => {
201
+ await page.goto("/login");
202
+
203
+ // One snapshot replaces 5+ individual assertions
204
+ await expect(page.getByRole("main")).toMatchAriaSnapshot(`
205
+ - heading "Sign In" [level=1]
206
+ - textbox "Email"
207
+ - textbox "Password"
208
+ - button "Sign In"
209
+ - link "Forgot password?"
210
+ `);
211
+ });
212
+
213
+ test("shows validation errors on empty submit", async ({ page }) => {
214
+ await page.goto("/login");
215
+ await page.getByRole("button", { name: /sign in/i }).click();
216
+
217
+ await expect(page.getByRole("form")).toMatchAriaSnapshot(`
218
+ - textbox "Email"
219
+ - text "Email is required"
220
+ - textbox "Password"
221
+ - text "Password is required"
222
+ - button "Sign In"
223
+ `);
224
+ });
225
+ });
226
+ ```
227
+
228
+ ## Locator Priority
229
+
230
+ Use locators that reflect how users and assistive technologies find elements. API names differ:
231
+
232
+ - **Playwright**: prefer `getByRole`, then `getByLabel`, `getByPlaceholder`, `getByText`,
233
+ `getByAltText`, and finally `getByTestId`.
234
+ - **Testing Library**: prefer `getByRole`, then `getByLabelText`, `getByPlaceholderText`,
235
+ `getByText`, `getByAltText`, and finally `getByTestId`.
236
+
237
+ If you can't find an element with semantic queries, the UI may have accessibility issues.
238
+
239
+ ## Anti-Patterns
240
+
241
+ ### Testing Only Implementation Details
242
+
243
+ Tests that only verify internals without validating meaningful behavior:
244
+
245
+ ```javascript
246
+ // BAD: Tests internal method exists, provides no behavior guarantee
247
+ it("has a validateFields method", () => {
248
+ expect(typeof form.validateFields).toBe("function");
249
+ });
250
+
251
+ // BAD: Asserts implementation without verifying outcome
252
+ it("calls the validator", () => {
253
+ expect(mockValidator).toHaveBeenCalledWith(data);
254
+ });
255
+
256
+ // GOOD: Tests observable behavior (acceptance)
257
+ it("prevents submission with invalid email", async () => {
258
+ await user.type(emailInput, "not-an-email");
259
+ await user.click(submitButton);
260
+ expect(screen.getByRole("alert")).toHaveTextContent(/valid email/i);
261
+ });
262
+
263
+ // ALSO GOOD: Tests implementation robustness (unit)
264
+ it("returns validation errors for malformed email", () => {
265
+ const result = validateEmail("not-an-email");
266
+ expect(result.valid).toBe(false);
267
+ expect(result.error).toBe("Invalid email format");
268
+ });
269
+ ```
270
+
271
+ The key distinction: implementation tests should verify _meaningful_ behavior of units, not just that code paths execute.
272
+
273
+ ### Circular Validation
274
+
275
+ ```javascript
276
+ // BAD: Test data derived from implementation
277
+ const expected = formatPrice(100); // Don't compute expected from code!
278
+ expect(formatPrice(100)).toBe(expected);
279
+
280
+ // GOOD: Expected value from requirements
281
+ expect(formatPrice(100)).toBe("$100.00");
282
+ ```
283
+
284
+ ### Over-Mocking
285
+
286
+ ```javascript
287
+ import { vi } from "vitest";
288
+
289
+ // BAD: Mock everything, test nothing real
290
+ vi.mock("./api");
291
+ vi.mock("./utils");
292
+ vi.mock("./formatter");
293
+ // Now just testing mocks talk to each other
294
+
295
+ // GOOD: Mock only external boundaries
296
+ // Mock: APIs, databases, time, file system
297
+ // Real: Business logic, components, formatters
298
+ ```
299
+
300
+ ### Brittle Selectors
301
+
302
+ ```javascript
303
+ // BAD: Implementation-dependent selectors
304
+ page.locator(".btn-primary.submit-form");
305
+ page.locator("#root > div > form > button:nth-child(3)");
306
+
307
+ // GOOD: Semantic locators
308
+ page.getByRole("button", { name: /submit order/i });
309
+ ```
310
+
311
+ ## Failing Tests Mean Bugs (Usually)
312
+
313
+ When a test fails, the investigation depends on the test type:
314
+
315
+ **Acceptance test fails:**
316
+
317
+ 1. Check the code under test first — likely a real bug
318
+ 2. Verify the test still matches current requirements — requirements may have changed
319
+ 3. Only update the test after confirming the new behavior is correct
320
+
321
+ **Implementation test fails:**
322
+
323
+ 1. If you're refactoring, the test may legitimately need updating
324
+ 2. If you're not refactoring, check the code — likely a bug
325
+ 3. Consider whether the test is too tightly coupled to implementation
326
+
327
+ Don't reflexively update tests to pass. Investigate why they fail.
328
+
329
+ ## Checklist Before Submitting Tests
330
+
331
+ - [ ] Each acceptance criterion has at least one test
332
+ - [ ] Edge cases from criteria are covered
333
+ - [ ] Implementation tests added for complex logic, error handling, boundary conditions
334
+ - [ ] Tests are named descriptively (criteria-based or behavior-based)
335
+ - [ ] Using semantic locators (getByRole, getByLabelText)
336
+ - [ ] No tests that only verify "code runs" without validating meaningful behavior
337
+ - [ ] Failing tests investigated appropriately (acceptance vs implementation)
338
+ - [ ] Accessibility checks included for interactive components
339
+ - [ ] Consider ARIA snapshots for structure validation (consolidates multiple assertions)
340
+
341
+ ## References
342
+
343
+ Load these files for detailed guidance:
344
+
345
+ - `references/locator-strategies.md` — Complete locator hierarchy with examples
346
+ - `references/aria-snapshots.md` — Structure validation, consolidating assertions
347
+ - `references/accessibility-testing.md` — axe-core integration, WCAG targeting
348
+ - `references/visual-regression.md` — Screenshot testing, baseline management
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Frontend Testing"
3
+ short_description: "Test frontend behavior, visuals, and accessibility."
4
+ default_prompt: "Use $frontend-testing to add focused coverage for this frontend change."