茉莉花单元测试抽象类

时间:2017-04-19 15:43:07

标签: unit-testing angular jasmine

有没有办法为抽象组件创建茉莉花单元测试?

const fixture = TestBed.createComponent(MyAbstractComponent);

说,"不能将抽象构造函数类型分配给非抽象构造函数类型"

我尝试了一些搜索但没有出现。

2 个答案:

答案 0 :(得分:5)

您可以在测试文件中创建一个简单的类,它从抽象类扩展(不要忘记模拟抽象方法),而不仅仅是测试它的非抽象方法。我们说MyAbstractClass

export abstract class MyAbstractClass {
  sum(a: number, b: number): number {
    return a + b;
  }

  abstract calc1(): void;
  abstract calc2(): void;
}

然后在spec文件中我们可以创建一个新的派生类:

class MyClass extends MyAbstractClass {
  // just mock any abstract method
  calc1(): void {
    return;
  }
  calc2(): void {
    return;
  }
}

所以现在我们可以为非抽象方法编写测试:

describe('MyAbstractClass', () => {
  let myClass: MyClass;
  beforeEach(() => {
    myClass = new MyClass();
  });

  it('sum two args', () => {
    const a = 1, b = 2;

    const sum = myClass.sum(a, b);

    expect(sum).toBe(3);
  });
});

还创建了此测试示例的stackblitz example

答案 1 :(得分:0)

这就是我测试使用内置抽象类SafePipe的角管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');
  });

});