![](/img/trans.png)
[英]Angular 6 unit testing component with DomSanitizer dependency
[英]How to use a DomSanitizer inside a unit test, if the component does not inject it?
我有一个简单的组件,它不注入 DomSanitizer。 假设它是
export class ExampleComponent {
@Input()
public safeHtml: SafeHtml | undefined;
}
如何在单元测试中使用 DomSanitizer? 我试过提供并注入它。 这是我的 spec.ts 文件:
describe('ExampleComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
let sanitizer: DomSanitizer;
await TestBed.configureTestingModule({
beforeEach(async() => {
declarations: [ExampleComponent],
providers: [DomSanitizer] // it is not injected by ExampleComponent
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
sanitizr = TestBed.inject(DomSanitizer); // my attempt, though...
});
it('should work with SafeHtml input', () => {
expect(component).toBeTruthy();
let text = 'bla­bla';
let safeText: SafeHtml = sanitizer.bypassSecurityTrustHtml(text); // TypeError here
component.safeHtml = safeText;
expect(true);
});
}
TypeError 说: TypeError: sanitizr.bypassSecurityTrustHtml is not a function
。
有没有办法在测试台中使用真正的 DoMSanitizer,即使实际组件不使用它?
我通过注入DomSanitizer
并将其从测试台的providers: []
数组中删除来让它工作。
describe('ExampleComponent', () => {
let component: ExampleComponent;
let fixture: ComponentFixture<ExampleComponent>;
let sanitizer: DomSanitizer;
await TestBed.configureTestingModule({
beforeEach(async() => {
declarations: [ExampleComponent],
}).compileComponents();
sanitizr = TestBed.inject(DomSanitizer); // injecting it here
});
beforeEach(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should work with SafeHtml input', () => {
expect(component).toBeTruthy();
let text = 'bla­bla';
let safeText: SafeHtml = sanitizer.bypassSecurityTrustHtml(text); // no more typeError
component.safeHtml = safeText;
fixture.detectChanges();
expect(component.safeHtml).toEqual({"changingThisBreaksApplicationSecurity": "blabla"});
let p = fixture.nativeElement.querySelector('p'); // my ExampleComponent shows the safeHtml variable inside a paragraph.
expect(p.innerHtml).toEqual('blabla');
});
}
请注意,返回的 SafeHtml 变量的内容有趣地变成了带有{"changingThisBreaksApplicationSecurity": ...}
的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.