变量始终未定义,等待Jasmine



我需要测试一个函数,在该函数中创建一个变量并为其赋值。

但是有效载荷常数总是未定义的。

活动卡片组件.ts

async ngOnInit() {
const { uid } = await this.auth.currentUser
const { payload } = await this.firestore.surveysUsers(this.survey.id).doc(uid).snapshotChanges().pipe(first()).toPromise();
this.completed = payload.exists
}

组件卡.组件.规范

beforeEach(waitForAsync(() => {
fireStoreServiceMock.surveysUsers.and.returnValue({ 
doc: () => { return {
snapshotChanges: () => { return {
pipe: () => { return {
toPromise: () => { return { exists: true }}
}}
}}
}}
});
}));
describe('tests in delete', () => {
it('should update surveys', fakeAsync(() => {
fixture.detectChanges();
component.delete().then(() => {
});
fixture.detectChanges();
tick();
expect(fireStoreServiceMock.surveys).toHaveBeenCalled();
expect(snackBarMock.open).toHaveBeenCalled();
}));
});

错误

Error: Uncaught (in promise): TypeError: Cannot read property 'exists' of undefined
TypeError: Cannot read property 'exists' of undefined
at CampaignsCardComponent.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/modules/campaigns/pages/campaigns-card/campaigns-card.component.ts:43:4)
at Generator.next (<anonymous>)
at fulfilled (http://localhost:9876/_karma_webpack_/webpack:/node_modules/tslib/tslib.es6.js:71:42)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:372:1)
at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/proxy.js:126:1)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:371:1)
at Object.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:28535:1)
at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:371:1)
at Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:134:1)
at http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:1276:1

差不多到了。问题是,这是一个可观察的,不应该嘲笑它上的pipe函数,而是从函数调用中返回一个可观测的。

试试这个:

import { of } from 'rxjs';
....
beforeEach(waitForAsync(() => {
fireStoreServiceMock.surveysUsers.and.returnValue({ 
doc: () => { return {
snapshotChanges: () => of({ exists: true }) // mock the observable with of
}}
}}
});
}));

我可能把括号({}(和更改搞砸了,但应该这样做。

最新更新