我们的代码使用Angular5和Ionic 3时遇到问题。
在我们的项目中,我们使用插件与相机进行交互以扫描名片。扫描完成后,我们需要显示Ionic Loading以告诉用户他的照片正在上传。此功能在移动设备上运行良好,但该功能的单元测试失败。
以下是用户扫描名片时执行的代码示例:
public scanBusinessCard(fab?: FabContainer): void {
if (fab) fab.close();
let that: ContactListPage = this;
this.scanService.scanBusinessCard().pipe(
concatMap((picture: string) => {
this.loading = this.loadingCtrl.create({
content: this.uploadingText,
});
this.loading.present();
return this.scanService.saveBusinessCard(picture);
}),
).subscribe({
next: (data) => {
that.loading.dismiss();
this.createModal('ContactEditionPage', {contactId: data.contact}, () => {
this.loadContacts();
});
},
error: (error) => {
if (error === 'No Image Selected') {
that.loading.dismiss();
return;
}
this.errorHandlerService.handleError(error);
},
});
}
在concatMap
部分,this
的类型为SafeSubscriber
,因此我们无法访问我们对象的变量。 < / p>
我们认为这与我们用于测试的mock
相关,这里是ScanServiceMock
代码:
import { Observable } from 'rxjs/Observable';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
export class ScanServiceMock {
// The picture returned by scanBusinessCard
public picture: string = '';
public raiseErrorOnScan: boolean = false;
public raiseErrorOnSave: boolean = false;
public scanBusinessCardSpy: jasmine.Spy;
public saveBusinessCardSpy: jasmine.Spy;
constructor() {
this.scanBusinessCardSpy = spyOn(this, 'scanBusinessCard').and.callThrough();
this.saveBusinessCardSpy = spyOn(this, 'saveBusinessCard').and.callThrough();
}
public scanBusinessCard(): Observable<string> {
if (this.raiseErrorOnScan) {
return ErrorObservable.create('Error');
}
return Observable.of(this.picture);
}
public saveBusinessCard(): Observable<void> {
if (this.raiseErrorOnSave) {
return ErrorObservable.create('Error');
}
return Observable.of();
}
}
我们做错了吗?我们尝试let that = this
,但在concatMap
部分内,that
为undefined
。有什么想法吗?