您可以使用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
测试覆盖率: