Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

typescript - How to inject Document in service?

I have an Angular 2 application. For mocking the Document object in tests, I'd like to inject it to the service like:

import { Document } from '??' 

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

The Title service of Angular uses the internal getDOM() method.

Is there any simple way to inject the Document to the service? Also, how should I reference it in the providers array?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
  ]));

  ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...