How to inject Document in service?

This has been supported by Angular for a while.

You can use the DOCUMENT constant provided by the @angular/common package.

Description of the DOCUMENT constant (taken from the API documentation):

A DI Token representing the main rendering context. In a browser, this is the DOM Document.

An example is as shown below:

my-service.service.ts:

import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable()
export class MyService {
  constructor(@Inject(DOCUMENT) private document: Document) {}
}

my-service.service.spec.ts

import { provide } from '@angular/core';
import { DOCUMENT } from '@angular/common';

import { MyService } from './my-service';

class MockDocument {}

describe('MyService', () => {
  beforeEachProviders(() => ([
    provide(DOCUMENT, { useClass: MockDocument }),
    MyService
  ]));

  ...
});

Leave a Comment