Angular版本:8.1.2
测试工具:Karma和Jasmine,已预先安装ng new
我目前正在从事我的第一个Angular项目。作为其一部分,我创建了一个调用的管道DomSanitizer.bypassSecurityTrustResourceUrl
。我这样做是为了能够在iframe中使用它们。我现在要对此管道实施测试。这是它的代码:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from "@angular/platform-browser";
@Pipe({
name: 'safe'
})
export class SafeResourceUrlPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url: string): SafeResourceUrl | string {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
自动生成的规格文件仅如下所示:
import { TestBed, async } from '@angular/core/testing';
import { SafeResourceUrlPipe } from './safe-resource-url.pipe';
import { DomSanitizer } from '@angular/platform-browser';
describe('Pipe: SafeResourceUrle', () => {
it('should create an instance', () => {
let pipe = new SafeResourceUrlPipe();
expect(pipe).toBeTruthy();
});
});
VSCode在我进行测试之前就告诉我这是行不通的,因为SafeResourceUrlPipe
的构造函数需要一个参数。到目前为止很好,但是我不知道现在该怎么办。我不能只使用new DomSanitizer
,因为它是一个抽象类。
我尝试过的是创建一个实现DomSanitizer的模拟类,但是这样做除了测试管道是否已创建外,我所做的工作不多,而且我早就知道了。我想测试的是它是否正确地完成了输入转换的工作,但是当我伪实现主要依赖项时,我几乎无法测试。
我已经对此进行了一些Google搜索,但我怀疑它会变得很明显,但我找不到它。
我建议使用Angular Testbed注入类似dom消毒剂的模拟物。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SafeResourceUrlPipe],
providers: [
SafeResourceUrlPipe,
{ provide: DomSanitizer, useValue: {bypassSecurityTrustResourceUrl(){}}
]
});
}));
然后
describe('Pipe: SafeResourceUrle', () => {
it('should create an instance', () => {
let pipe = TestBed.get(SafeResourceUrlPipe);
expect(pipe).toBeTruthy();
});
});
ps在useValue
这里很重要。如果您仅在此处提供值,则可以。如果要用一个完整的模拟类替换它,则必须useClass
(大多数人卡住的小地方)
export class MockDomSanitizer {
bypassSecurityTrustResourceUrl() {}
otherMethods(){}
}
这应该允许您使用模拟的dom消毒程序方法来运行管道。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句