简体   繁体   English

Angular 8 - 抽象服务的单元测试

[英]Angular 8 - Unit test for abstract service

I should write a unit test for an abstract service.我应该为抽象服务编写单元测试。 We have couple of SSE channels in the application and we created base SSE service to be extended and it provides some basic functionality.我们在应用程序中有几个 SSE 通道,我们创建了要扩展的基础 SSE 服务,它提供了一些基本功能。

export abstract class BaseSseService {
  protected zone: NgZone;

  protected sseChannelUrl: string;

  private eventSource: EventSource;
  private reconnectFrequencySec: number = 1;
  private reconnectTimeout: any;

  constructor(channelUrl: string) {
    const injector = AppInjector.getInjector();
    this.zone = injector.get(NgZone);
    this.sseChannelUrl = channelUrl;
  }

  protected abstract openSseChannel(): void;
  //...
}

Now, before it was made abstract unit test were running.现在,在它被制作之前,抽象单元测试正在运行。 Once I changed it to the abstract class, I'm getting this error while trying to run should be created test: Error: Can't resolve all parameters for TestBaseSseService: (?).一旦我将其更改为抽象 class,我在尝试运行时遇到此错误should be created测试: Error: Can't resolve all parameters for TestBaseSseService: (?).

My test looks like this:我的测试如下所示:

class TestBaseSseService extends BaseSseService {
  openSseChannel() {
    console.log('Test');
  }
}

fdescribe('BaseSseService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        TestBaseSseService,
        Injector,
        { provide: String, useValue: "test" }
      ]
    });
    AppInjector.setInjector(TestBed.get(Injector));
  })

  describe(':', () => {
    function setup() {
      return TestBed.get(TestBaseSseService)
    }

    it('should be created', () => {
      const service = setup();
      expect(service).toBeTruthy();
    });
  });  
});

The question is, should I even bother with unit test for abstract service and if so how to solve this issue?问题是,我是否应该为抽象服务进行单元测试,如果是,如何解决这个问题? As you can see, mocking the service does not solve this nor does adding BaseSseService to TestBed providers.如您所见,mocking 该服务没有解决这个问题,也没有将BaseSseService添加到TestBed提供程序。

It's trying to provide the channelUrl from the abstract class, but this is obviously not a provider or an InjectionToken.它试图从抽象 class 中提供channelUrl ,但这显然不是提供者或 InjectionToken。

You can change your service to handle this:您可以更改您的服务来处理此问题:

class TestBaseSseService extends BaseSseService {
  constructor() {
    super('url');
  }

  openSseChannel() {
    console.log('Test');
  }
}

And yes, it's always good to test an abstract class.是的,测试一个抽象的 class 总是好的。 This way you can be sure-ish that whenever you implement it, it will act the same (when tested properly)通过这种方式,您可以确定无论何时实施它,它都会发挥相同的作用(如果测试得当)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM