You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -573,3 +573,77 @@ public class FocussingInputTest : ComponentTestFixture
573
573
```
574
574
575
575
The last line verifies that there was a single argument to the invocation, and via the `ShouldBeElementReferenceTo` checks, that the `<input />` was indeed the referenced element.
576
+
577
+
## Testing components with injected dependencies
578
+
579
+
The demonstrate service injection, lets refactor the [FetchData.razor](../sample/src/Pages/FetchData.razor) component that comes with the default Razor app template, to make it more testable:
580
+
581
+
- Extract an interface from [WeatherForecastService](../sample/src/Data/WeatherForecastService.cs), name it [IWeatherForecastService](../sample/src/Data/IWeatherForecastService.cs), and have `FetchData` take a dependency on it.
582
+
583
+
- Extract the `<table>` inside the `else` branch in the [FetchData.razor](../sample/src/Pages/FetchData.razor) component into its own component. Lets name it [ForecastDataTable](../sample/src/Pages/FetchData.razor).
584
+
585
+
- In the [FetchData.razor](../sample/src/Pages/FetchData.razor), pass the variable `forecasts` to the [ForecastDataTable](../sample/src/Pages/FetchData.razor) component.
586
+
587
+
Now we just need a [MockForecastService.cs](../sample/tests/MockForecastService.cs). It looks like this:
- In `Test001` we use the `Services.AddService` method to register the dependency and the performs a regular "initial render" verification.
646
+
647
+
-`Test002` creates a new instance of the mock service and registers that with the the service provider. It then renders the CUT and uses `WaitForNextRender` to pass the test data to the mock services task, which then completes and the CUT gets the data.
648
+
649
+
- In the assert step we expect the CUT to use a `ForecastDataTable` to render the forecast data. Thus, to make our assertion more simple and stable to changes, we render an instance of the `ForecastDataTable` use that to verify that the expected addition after the CUT receives the forecast data is as it should be.
0 commit comments