|
| 1 | +--- |
| 2 | +sidebar_label: 3. Vitest Browser Mode |
| 3 | +--- |
| 4 | + |
| 5 | +# Recipe Search Shallow with Vitest Browser Mode |
| 6 | + |
| 7 | +## Setup |
| 8 | + |
| 9 | +```sh |
| 10 | +pnpm cook start 303-recipe-search-shallow-browser-mode |
| 11 | +``` |
| 12 | + |
| 13 | +:::info β»οΈ TDD option |
| 14 | + |
| 15 | +You can choose to: |
| 16 | + |
| 17 | +- go full-on TDD and implement the tests first then checkout the implementation later, |
| 18 | +- or checkout the implementation first and then implement the tests. |
| 19 | + |
| 20 | +::: |
| 21 | + |
| 22 | +## π― Goal: Test `RecipeSearch` |
| 23 | + |
| 24 | +`RecipeSearch` component should fetch recipes using `RecipeRepository` on startup and display them using `RecipePreview` component. |
| 25 | +But, this time, let's check that the loaded recipes are forwarded as inputs to children. |
| 26 | + |
| 27 | +**Implement tests** for `RecipeSearch` and make sure that: |
| 28 | + |
| 29 | +- recipes are passed to child components. |
| 30 | + |
| 31 | +### π Steps |
| 32 | + |
| 33 | +#### 1. Run tests: |
| 34 | + |
| 35 | +```sh |
| 36 | +pnpm test |
| 37 | +``` |
| 38 | + |
| 39 | +#### 2. Open `src/app/recipe/recipe-search.shallow.spec.ts`. |
| 40 | + |
| 41 | +#### 3. Override component's imports & schema: |
| 42 | + |
| 43 | +```ts |
| 44 | +TestBed.overrideComponent(RecipeSearch, { |
| 45 | + set: { |
| 46 | + imports: [], |
| 47 | + schemas: [CUSTOM_ELEMENTS_SCHEMA], |
| 48 | + }, |
| 49 | +}); |
| 50 | +``` |
| 51 | + |
| 52 | +#### 4. Query DOM and check child components properties. |
| 53 | + |
| 54 | +- Cf. [Query DOM with Vitest Browser Mode](#-tip-how-to-query-the-dom-and-make-assertions-with-vitest-browser-mode) |
| 55 | +- Cf. [Access element properties](#-tip-access-element-properties) |
| 56 | + |
| 57 | +:::tip |
| 58 | +Note that `RecipePreview` component host element has a `data-testid="recipe-preview"` attribute that you can query with Testing Library. |
| 59 | +::: |
| 60 | + |
| 61 | +#### 5. [optional] Checkout the implementation if you've opted for TDD option:. |
| 62 | + |
| 63 | +```sh |
| 64 | +pnpm cook checkout-impl |
| 65 | +``` |
| 66 | + |
| 67 | +#### 6. β
Make sure tests are passing. |
| 68 | + |
| 69 | +## π Appendices |
| 70 | + |
| 71 | +### π Tip: How to query the DOM and make assertions with Vitest Browser Mode |
| 72 | + |
| 73 | +- β‘οΈ Querying with Vitest Browser Mode: https://vitest.dev/guide/browser/locators.html |
| 74 | +- β‘οΈ Asserting with Vitest Browser Mode: https://vitest.dev/guide/browser/assertion-api.html |
| 75 | + |
| 76 | +### π Tip: Access element properties |
| 77 | + |
| 78 | +You can transform any `HTMLElement` into an Angular `DebugElement` to access the properties forwarded by parent component: |
| 79 | + |
| 80 | +```ts |
| 81 | +const elements = page.getByXXX().elements(); |
| 82 | + |
| 83 | +const myItems = elements.map((el) => new DebugElement(el).properties.myItem); |
| 84 | +``` |
0 commit comments