[英]How to use a DomSanitizer inside a unit test, if the component does not inject it?
I have a simple component, which does not inject the DomSanitizer.我有一个简单的组件,它不注入 DomSanitizer。 Let's say it is
假设它是
export class ExampleComponent {
@Input()
public safeHtml: SafeHtml | undefined;
}
How can I use the DomSanitizer inside a unit test?如何在单元测试中使用 DomSanitizer? I've tried providing and injecting it.
我试过提供并注入它。 Here goes my spec.ts file:
这是我的 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);
});
}
The TypeError says: TypeError: sanitizr.bypassSecurityTrustHtml is not a function
. TypeError 说:
TypeError: sanitizr.bypassSecurityTrustHtml is not a function
。
Is there a way to make use of a real DoMSanitizer in a testbed even if the real component does not use it?有没有办法在测试台中使用真正的 DoMSanitizer,即使实际组件不使用它?
I got it to work by injecting the DomSanitizer
and by removing it from the testbed's providers: []
array.我通过注入
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');
});
}
Note the returned SafeHtml variable's content became interestingly an object with {"changingThisBreaksApplicationSecurity": ...}
.请注意,返回的 SafeHtml 变量的内容有趣地变成了带有
{"changingThisBreaksApplicationSecurity": ...}
的 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.