来自issue:
spyOnProperty 旨在用于已使用 Object.defineProperty 的对象,因为它是通过其背后的函数实现的,并且不能通过分配给它来修改。如果你只有一个对象的基本属性,你应该能够分配它们。
您可以只为component.transfers$ 属性分配一个存根值。
例如
component.ts:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { TransfersService } from './TransfersService';
export type AppResponseError = any;
type Transfer = any;
@Component({
selector: 'app-transfer',
})
export class TransferComponent implements OnInit {
transfers$: Observable<Transfer[] | AppResponseError>;
constructor(private transfersService: TransfersService) {
this.transfers$ = this.transfersService.transfers$;
}
ngOnInit() {
this.transfers$.subscribe((data) => {
console.log(data);
});
}
}
TransferService.ts:
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
@Injectable()
export class TransfersService {
transfers$ = of('real observable');
}
component.test.ts:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { AppResponseError, TransferComponent } from './component';
import { TransfersService } from './TransfersService';
fdescribe('65208911', () => {
let component: TransferComponent;
let fixture: ComponentFixture<TransferComponent>;
const transfersServiceStub = {
transfers$: of(),
};
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TransferComponent],
providers: [
{ provide: TransfersService, useValue: transfersServiceStub },
],
});
fixture = TestBed.createComponent(TransferComponent);
component = fixture.componentInstance;
});
it('should hide app-checklist component when return AppResponseError', () => {
const error: AppResponseError = {
code: '400',
message: 'Bad request',
};
component.transfers$ = of(error);
fixture.detectChanges();
// expect(fixture.debugElement.query(By.css('app-checklist'))).toBeNull();
});
});
单元测试结果:
LOG: Object{code: '400', message: 'Bad request'}
Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 0 of 15 SUCCESS (0 secs / 0 secs)
WARN: 'Spec '65208911 should hide app-checklist component when return AppResponseError' has no expectations.'
Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 0 of 15 SUCCESS (0 secs / 0 secs)
Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 1 of 15 (skipped 14) SUCCESS (0.086 secs / 0.026 secs)
TOTAL: 1 SUCCESS