Angular Jasmine测试具有专用服务的服务存根,然后检查是否调用了专用服务的功能?

时间:2018-11-19 00:08:33

标签: angular jasmine angular-testing

我正在测试角度组件,其中一个功能是调用私有的“通知服务”。无论如何,我出于测试期间的各种原因都会为此服务提供存根。

现在我遇到的问题是,尝试对其进行简单检查时,仍然出现错误[1 2 3 4 5] [2 4 6 4 5] .

'notification is a private service'

在我的测试台上,我有:

expect(component.notification.done()).toHaveBeenCalled();

在我的NotificationStub类中,我只包含带有返回的函数;

如果该服务是私有的,如何检查该函数是否正在被调用?由于各种可维护性的原因,我不想将其公开。

1 个答案:

答案 0 :(得分:0)

您可以使用 const doneSpy = spyOn(NotificationStub.prototype, 'done') 将间谍安装到 done 方法上。然后,您可以对 doneSpy 进行断言,而不是尝试获取私有服务。

以下是使用 angular v11+ 的示例:

example.component.ts

import { Component, OnInit } from '@angular/core';
import { NotificationService } from './notification.service';

@Component({})
export class ExampleComponent implements OnInit {
  constructor(private notification: NotificationService) {}

  ngOnInit() {
    this.notification.done();
  }
}

notification.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class NotificationService {
  done() {
    console.log('Your real implementation');
  }
}

example.component.spec.ts

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ExampleComponent } from './example.component';
import { NotificationService } from './notification.service';

class NotificationStub {
  done() {
    console.log('fake implementation');
  }
}

fdescribe('53366751', () => {
  let fixture: ComponentFixture<ExampleComponent>;
  let component: ExampleComponent;
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ExampleComponent],
        providers: [
          { provide: NotificationService, useClass: NotificationStub },
        ],
      })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(ExampleComponent);
          component = fixture.componentInstance;
        });
    })
  );

  it('should pass', () => {
    const doneSpy = spyOn(NotificationStub.prototype, 'done').and.callThrough();
    fixture.detectChanges();
    expect(doneSpy).toHaveBeenCalled();
  });
});

单元测试结果:

LOG: 'fake implementation'
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 0 of 36 SUCCESS (0 secs / 0 secs)
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 36 (skipped 34) SUCCESS (0.105 secs / 0.024 secs)
TOTAL: 2 SUCCESS

测试覆盖率:

enter image description here