Jasmine Unit Test Abstract class

后端 未结 2 796
旧时难觅i
旧时难觅i 2021-02-07 17:20

Is there a way to create a jasmine unit test for an abstract component?

doing

const fixture = TestBed.createComponent(MyAbstractComponent);
2条回答
  •  孤城傲影
    2021-02-07 18:22

    Here is what I did to test an angular pipe SafePipe that was using a built in abstract class DomSanitizer.

    // 1. Import the pipe/component to be tested
    import { SafePipe } from './safe.pipe';
    // 2. Import the abstract class
    import { DomSanitizer } from '@angular/platform-browser';
    
    // 3. Important step - create a mock class which extends 
    // from the base class imported above and add implement 
    // the mock methods
    class MockDomSanitizer extends DomSanitizer {
      sanitize(): string{
        return 'ANY';
      }
      bypassSecurityTrustHtml(): string{
        return 'ANY'
      }
      bypassSecurityTrustStyle(): string{
        return 'ANY'
      }
      bypassSecurityTrustScript(): string{
        return 'ANY'
      }
      bypassSecurityTrustUrl(): string{
        return 'ANY'
      }
      bypassSecurityTrustResourceUrl(): string{
        return 'ANY'
      }
    }
    
    describe('SafePipe', () => {
    
      it('should return an HTML string', () => {
        // 4. create an instance of pipe class and inject the mocked class above
        let safePipe = new SafePipe(new MockDomSanitizer());
    
        // 5. Add your asserions as ususal
        expect(safePipe.transform(null, 'html')).toBeTruthy();
        expect(safePipe.transform(null, 'style')).toBeTruthy();
        expect(safePipe.transform(null, 'script')).toBeTruthy();
        expect(safePipe.transform(null, 'url')).toBeTruthy();
        expect(safePipe.transform(null, 'resourceUrl')).toBeTruthy();
        expect(safePipe.transform(null, 'anything')).toContain('anything');
      });
    
    });

提交回复
热议问题