Jasmine Unit Test Abstract class

元气小坏坏 提交于 2019-12-05 20:54:08

问题


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

doing

const fixture = TestBed.createComponent(MyAbstractComponent);

says, "cannot assign an abstract constructor type to a non-abstract constructor type"

I tried some searching but nothing comes up.


回答1:


You can create a simple class in your test file which extends from abstract class (do not forget to mock abstract methods), than just test its non abstract methods. Let's say we have MyAbstractClass:

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

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

and then in spec file we can just create a new derived class:

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

So now we can write tests for non-abstract methods:

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);
  });
});

Also created a stackblitz example of this test example.



来源:https://stackoverflow.com/questions/43500351/jasmine-unit-test-abstract-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!