在ngOnInit
中,我有一个具有某些逻辑的组件,
this.service.getCars(this.companyId).subscribe(cars => {
if(cars) this.companyCars = cars.sort( (a, b) => {
let alpha = a.car.toLowerCase()
let beta = b.car.toLowerCase()
return (alpha < beta) ? -1 : (alpha > beta) ? 1 : 0
})
})
这是它的服务</ p>
public getCars(companyId: string): Observable<any> {
return this.http.get<Car[]>(`${this.api}?companyId=${companyId}`, this.httpOptions)
}
我正在尝试在我的测试中使用模拟服务来测试此代码块,该服务将返回汽车模拟。我还要确保在我的提供程序中提供模拟服务,并从TestBed那里获得
component.spec.ts
class MockService {
getCars = () => of(mockCars)
}
...
describe('CarComponent', () => {
let component: CarComponent
let fixture: ComponentFixture<CarComponent>
let service: CarService
...
providers: [
{
provide: CarService, useClass: MockService
},
]
...
service = TestBed.get(CarService)
这里是模拟:
export const mockCars = [
{
car: "Toyota",
color: "Red"
},
{
car: "Honda",
color: "Blue"
},
{
car: "Ford",
color: "Green"
}
]
现在,在我的测试块中,我似乎无法重新获得模拟数组来对其进行测试。
it('should get and sort cars', async () => {
await component.ngOnInit()
console.log(component.companyCars) // shows empty
expect(component.companyCars.length).toBe(3) // gives expected 0 to be 3
// spyOn(service, 'getCars')
// fixture.detectChanges()
// console.log(component.cmpanyCars)
})
我希望我的模拟服务以可观察的方式返回我的模拟数据,以便我可以订阅和测试它,但它不会在我的组件中填充最初为空的companyCars数组。