我正在尝试测试一个组件,该组件调用Service内的方法,该方法调用Http
调用以获取数据。尝试运行测试时,observable方法从不发出数据,也不会通过断言表明数据未定义。
我尝试使用FakeAsync
,flush
,tick
甚至Jasmine-Marbles
模拟一个时间间隔,以等待Observable发出数据然后进行测试。
uploads.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UploadsService {
product: string;
BASE_URL: string;
constructor(private http: HttpClient, @Inject('user') private user: any)
{
this.product = user.product;
this.BASE_URL = `/upload/${this.product}/`;
}
retrieve(): Observable<any> {
return this.http.get(this.BASE_URL + '/getFileList');
}
}
uploads.component.ts
@Component({
selector: 'app-uploads',
templateUrl: './uploads.component.html',
providers: [UploadsService]
})
export class UploadsComponent {
isLoading: boolean = true;
fileList;
asOfDate;
constructor(private uploadsService: UploadsService) {}
public retrieveFiles() {
this.uploadsService
.retrieve()
.finally(() => {
this.isLoading = false;
})
.subscribe(
data => {
this.fileList = data['fileList'];
this.asOfDate = data['asofDate'];
},
error => {
console.log('Error Occurred!');
}
);
}
}
uploads.component.spec.ts
function mockUser() {
return {
product: 'stackoverflow'
}
}
describe('Uploads Component', () => {
let component: UploadsComponent;
let fixture: ComponentFixture<UploadsComponent>;
let service: UploadsService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [UploadsComponent],
providers: [
{ provide: 'user', useValue: mockUser },
{
provide: UploadsService,
useValue: new UploadsService(null, mockUser)//is this right to do?
}
], schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UploadsComponent);
component = fixture.componentInstance;
service = TestBed.get(UploadsService);
});
// Tests that failed
it('service retrieve method was called', () => {
spyOn(service, 'retrieve');
component.retrieveFiles();
expect(service.retrieve).toHaveBeenCalled();
});
it('retrieve returns expected asOfDate', () => {
spyOn(service, 'retrieve')
.and.returnValue(Observable.of({ asOfDate: '7/7/2019'}));
component.retrieveFiles();
expect(component.asOfDate).toBe('7/7/2019'); //asOfDate was 'undefined'
})
});
我试图用来测试retrieveFiles
中的UploadsComponent
方法的两个基本单元测试用例都失败了。
我尝试使用以下方法:
1)fixture.detectChanges()
2)使用FakeAsync
和tick
模拟时间流逝。
这些解决方案对我来说还没有解决。任何线索都会很棒。