测试管道对服务的依赖 [英] Test pipe with dependencies on services
问题描述
我有一个管道,可以对HTML进行如下处理:
I have a pipe that sanatises HTML as below:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'sanitiseHtml'
})
export class SanitiseHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {}
transform(value: any): any {
return this._sanitizer.bypassSecurityTrustHtml(value);
}
}
我要按以下方式对其进行测试:
I want to test it as below:
describe('Pipe: Sanatiser', () => {
let pipe: SanitiseHtmlPipe;
beforeEach(() => {
pipe = new SanitiseHtmlPipe(new DomSanitizer());
});
it('create an instance', () => {
expect(pipe).toBeTruthy();
});
});
DomSanatizer是一个抽象类,通过将其传递给构造函数由typescript自动装配:
The DomSanatizer is an abstract class which is autowired by typescript by passing it into a constructor:
constructor(private _sanitizer: DomSanitizer) {}
当前我得到打字稿错误:
Currently I get the typescript errror:
无法创建抽象类'DomSanitizer'的实例。
Cannot create an instance of the abstract class 'DomSanitizer'.
有人实例化在Angular中传递给构造函数的依赖项时,有人知道吗?还是测试这种东西的方法是什么?
Does anyone know what typescript does when instantiating dependencies passed into a constructor in Angular? Or what the way to test something like this is?
推荐答案
由于管道中的DI,您需要配置测试环境(测试台)以解决依赖关系:
Because of the DI in your pipe, you need to configure a test environment (test bed) to resolve the dependency:
import { BrowserModule, DomSanitizer } from '@angular/platform-browser';
import { inject, TestBed } from '@angular/core/testing';
describe('SanitiseHtmlPipe', () => {
beforeEach(() => {
TestBed
.configureTestingModule({
imports: [
BrowserModule
]
});
});
it('create an instance', inject([DomSanitizer], (domSanitizer: DomSanitizer) => {
let pipe = new SanitiseHtmlPipe(domSanitizer);
expect(pipe).toBeTruthy();
}));
});
这篇关于测试管道对服务的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!