Jasmine 单元测试抽象类 [英] Jasmine Unit Test Abstract class

查看:21
本文介绍了Jasmine 单元测试抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在做

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.

推荐答案

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

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

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

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

还创建了 stackblitz这个测试示例的示例.

这篇关于Jasmine 单元测试抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆