您应该将 spy 安装到 this.service.getThings() 方法上并返回一个同步的 observable,其值立即可用。然后,您可以在组件的ngOnInit 方法上订阅它。最后,对otherProperty 进行断言以检查该值。欲了解更多信息,请参阅Component with async service
例如使用angular v11+
example.component.ts:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ExampleService } from './example.service';
@Component({
selector: 'app-example',
template: '<input [ngModel]="myObservable$ |async">',
})
export class ExampleComponent implements OnInit {
myObservable$: Observable<string>;
otherProperty: string;
constructor(private service: ExampleService) {}
ngOnInit() {
this.myObservable$ = this.service
.getThings()
.pipe(tap((value) => (this.otherProperty = value)));
}
}
example.service.ts
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable()
export class ExampleService {
constructor() {}
getThings() {
return of('your real implementation');
}
}
example.component.spec.ts:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { of } from 'rxjs';
import { ExampleComponent } from './example.component';
import { ExampleService } from './example.service';
fdescribe('65479995', () => {
let fixture: ComponentFixture<ExampleComponent>;
let component: ExampleComponent;
let exampleServiceSpy: jasmine.SpyObj<ExampleService>;
beforeEach(
waitForAsync(() => {
exampleServiceSpy = jasmine.createSpyObj('ExampleService', ['getThings']);
exampleServiceSpy.getThings.and.returnValue(of('fake implementation'));
TestBed.configureTestingModule({
declarations: [ExampleComponent],
imports: [FormsModule],
providers: [{ provide: ExampleService, useValue: exampleServiceSpy }],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleComponent);
component = fixture.componentInstance;
});
})
);
it('should pass', () => {
expect(component.otherProperty).toBeUndefined();
fixture.detectChanges();
expect(component.otherProperty).toBe('fake implementation');
expect(exampleServiceSpy.getThings).toHaveBeenCalled();
});
});
测试结果:
================================================================================
✔ Browser application bundle generation complete.
✔ Browser application bundle generation complete.
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 47 (skipped 45) SUCCESS (0.17 secs / 0.063 secs)
TOTAL: 2 SUCCESS