> For the complete documentation index, see [llms.txt](https://guide-angular.wishtack.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://guide-angular.wishtack.io/angular/testing/unit-testing/unit-test-dun-service.md).

# Unit-Test d'un Service

Il serait dommage de ne pas profiter de la [Dependency Injection](/angular/dependency-injection.md) lors de l'implémentation des tests unitaire.

## `TestBed.get` 👍

La méthode statique **`TestBed.get`** permet d'**injecter les services** dans les tests unitaires.

```typescript
describe('PickyWeatherStation', () => {

    it('should give temperature', fakeAsync(() => {

        const weatherStation: PickyWeatherStation = TestBed.get(PickyWeatherStation);

        let temperature;

        weatherStation.getTemperature('Lyon')
            .subscribe(_temperature => temperature = _temperature);

        expect(temperature).toBe(42);

    }));

});
```

{% hint style="success" %}
Pour éviter de récupérer l'instance dans chaque "spec", pensez à utiliser la fonction `beforeEach`!

```typescript
let weatherStation: PickyWeatherStation;
beforeEach(() => weatherStation = TestBed.get(PickyWeatherStation));
```

{% endhint %}

Pensez à définir un "Live Template" dans l'IDE.

![Angular Test Injection Live Template](/files/-LD_HfDPvUm98kCcWGL1)

## `inject` 👎

La fonction `inject` *(du module `@angular/core/testing`)* permet également d'injecter des services dans les tests unitaire.

Cette fonction prend deux paramètres :

* **la liste des tokens à injecter** *(généralement liste des classes à injecter),*
* **une fonction de "callback"** qui prend en paramètre **la liste des services injectés** dans le même ordre que la liste de tokens.

{% hint style="danger" %}
Attention à **ne pas confondre la fonction `inject`** du module **`@angular/core/testing`** avec celle du module **`@angular/core`** qui sert à injecter des services dans les factories `factory: () => new MyService(inject(MyDep))` *(Cf.* [*https://github.com/angular/angular/blob/master/packages/examples/core/di/ts/injector\_spec.ts#L70*](https://github.com/angular/angular/blob/master/packages/examples/core/di/ts/injector_spec.ts#L70)*)*.
{% endhint %}

{% tabs %}
{% tab title="picky-weather-station.ts" %}

```typescript
@Injectable({
    providedIn: 'root'
})
class PickyWeatherStation {

    getTemperature(city): Observable<number> {
        return of(42);
    }

}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="picky-weather-station.spec.ts" %}

```typescript
describe('PickyWeatherStation', () => {

    let weatherStation: PickyWeatherStation;

    beforeEach(inject([PickyWeatherStation], _weatherStation => weatherStation = _weatherStation));

    it('should give temperature', fakeAsync(() => {

        let temperature;

        weatherStation.getTemperature('Lyon')
            .subscribe(_temperature => temperature = _temperature);

        expect(temperature).toBe(42);

    }));

});
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
La fonction `inject` peut être utilisée **directement autour de la fonction de "spec"** mais il est généralement plus simple d'ajouter un **`beforeEach` pour chaque service** afin d'éviter les problèmes liés à l'ordre des tokens d'injection et le refactoring en général.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://guide-angular.wishtack.io/angular/testing/unit-testing/unit-test-dun-service.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
