簡體   English   中英

如果組件不注入,如何在單元測試中使用 DomSanitizer?

[英]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&shy;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&shy;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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM