在仅创建(实例化)具有DomSanitizer
依赖关系的组件的单元测试中,如何模拟/存根该依赖关系?
因为DomSanitizer
是一个Abstract
类,所以我不知道bypassSecurityTrustHtml
的方法签名是什么样子。
如果不是要模拟/存根DomSanitizer
,那么应该如何继续向抽象类中注入实际实现?
该组件中的实际陈述如下:
this.trustedString = <string>this.domSanitizer.bypassSecurityTrustHtml(trustedHTML);
TestBed
的设置如下:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
BrowserModule,
// other modules
],
providers: [
{
provide: DomSanitizer,
useValue: {
bypassSecurityTrustHtml: () => 'safeString'
}
},
// more providers
],
declarations: [ TheComponent ],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));
我在Chrome的Karma中遇到的具体错误(不是无头)是
TypeError: view.root.sanitizer.sanitize is not a function
错误属性:Object({ngDebugContext:DebugContext _({视图:Object({def:Object({工厂:函数,nodeFlags:16793601,rootNodeFlags:1,nodeMatchedQueries:0,标志:0,节点:[Object({ nodeIndex:0,父代:null,renderParent:空,bindingIndex:0,outputIndex:0,checkIndex:0,标志:1,childFlags:16793601,directChildFlags:16777217,childMatchedQueries:0,matchedQueries:Object({}),matchedQueryIds: 0,引用:Object({}),ngContentIndex:null,childCount:5,绑定:[],bindingFlags:0,输出:[],元素:Object({ns:null,名称:null,attrs:[],模板:null,componentProvider:null,componentView:null,componentRendererType:null,publicProviders:null({}),allProviders:null({}},handleEvent:Function}),provider:null,text:null,query:null, ngContent:null}},Object({nodeIndex:1,parent:Object({nodeIndex:0,parent:null,renderParent:null,bindingIndex:0,outputIndex:0,checkIndex:0,标志:1,childFlags:16793601,迪雷克tChildFlags:16777217 ... 在 在setElementProperty(webpack:///./node_modules/@angular/core/fesm5/core.js?:8237:61) 在checkAndUpdateElementValue(webpack:///./node_modules/@angular/core/fesm5/core.js?:8189:13) 在checkAndUpdateElementInline(webpack:///./node_modules/@angular/core/fesm5/core.js?:8136:24) 在checkAndUpdateNodeInline(webpack:///./node_modules/@angular/core/fesm5/core.js?:10477:20) 在checkAndUpdateNode(webpack:///./node_modules/@angular/core/fesm5/core.js?:10443:16) 在debugCheckAndUpdateNode(webpack:///./node_modules/@angular/core/fesm5/core.js?:11076:38) 在debugCheckRenderNodeFn(webpack:///./node_modules/@angular/core/fesm5/core.js?:11062:13) 在Object.eval [作为updateRenderer](ng:///DynamicTestModule/ConversationMessageComponent.ngfactory.js:84:5) 在Object.debugUpdateRenderer [作为updateRenderer](webpack:///./node_modules/@angular/core/fesm5/core.js?:11054:21) 在checkAndUpdateView(webpack:///./node_modules/@angular/core/fesm5/core.js?:10430:14)
答案 0 :(得分:9)
作为解决方法,请尝试添加sanitize: () => 'safeString',
...
useValue: {
sanitize: () => 'safeString',
bypassSecurityTrustHtml: () => 'safeString'
}
...
答案 1 :(得分:7)
如果要保留值,请使用:
{
provide: DomSanitizer,
useValue: {
sanitize: (ctx: any, val: string) => val,
bypassSecurityTrustResourceUrl: (val: string) => val,
},
}