私は予想通りの模擬試験からの約束拒否を処理していないコンポーネント単体テストを持っています。角試験部品 - 模擬試験からPromise.rejectを返すときのエラー
IはaddUserToOrganisation
にいくつかのデータを送信し、それを返すことを約束を処理するコンポーネントにこの機能を持っている:このコンポーネントをテストする場合
public onSubmit() {
this.saveStatus = 'Saving';
this.user = this.prepareSaveUser();
this._userService.addUserToOrganisation(this.user)
.then(() => this._router.navigate(['/profile']))
.catch(error => this.reportError(error));
}
、IはaddUserToOrganisation
にスパイUserService
ためのモックを提供していますエンドポイントといくつかの種類の約束を返します。
mockUserService = jasmine.createSpyObj('mockUserService', ['getOrgId', 'addUserToOrganisation']);
mockUserService.getOrgId.and.returnValue(Promise.resolve('an id'));
mockUserService.addUserToOrganisation.and.returnValue(Promise.resolve());
これは幸せなパス(解決)のために正常に動作します - 私はそうでthis._router.navigate()
が呼び出されたことをテストすることができ。この幸せなパスの合格テストは以下の通りです:
it('should navigate to /profile if save is successful', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
component.userForm.controls['firstName'].setValue('John');
component.userForm.controls['lastName'].setValue('Doe');
component.userForm.controls['email'].setValue('[email protected]');
component.onSubmit();
tick();
fixture.detectChanges();
expect(mockRouter.navigate).toHaveBeenCalledWith(['/profile']);
}));
しかし、私は 'sad'パスのテストに問題があります。私はonSubmit
で.catch
を持っているが、私は、Promise.reject
を返すために、私のモックを変更すると、私はこのエラーを取得しています:
Error: Uncaught (in promise): no
は、だからそれは混乱です。この悲しい道を私のテストはここにあります。私はモックコールの応答を変更することに注意してください。
it('should show Failed save status if the save function fails', fakeAsync(() => {
mockUserService.addUserToOrganisation.and.returnValue(Promise.reject('no'));
fixture.detectChanges();
tick();
fixture.detectChanges();
component.userForm.controls['firstName'].setValue('John');
component.userForm.controls['lastName'].setValue('Doe');
component.userForm.controls['email'].setValue('[email protected]');
component.onSubmit();
tick();
fixture.detectChanges();
expect(component.saveStatus).toEqual('Failed! no');
}));
誰にでもアイデアはありますか?
私は 'tick()'を削除しようとしましたが、まだエラーがあります。どのようにそれが不必要であるか私はかなり理解していない?しかし、私の模擬応答を 'returnValue ...'から 'callFake ...'に変更することは、このトリックを行っています。私はここでニュアンスを100%理解しているとは思わない。 – dafyddPrys
'callFake'は呼び出された時点で拒否された約束事を作成します。したがって、' component.onSubmit() '呼び出し中に' .catch'で連鎖され、処理された約束を得ます。'returnValue'は、直ちに' .catch'でチェーンされるべき既存の拒否された約束を受け入れますが、タイマーは 'tick()'で次のティックに移動されてから 'component.onSubmit()'に拒否されます。 'setTimeout'を使った例は、何が起こっているのかを正確に示しています。それは 'tick()'なしで動作するはずです。私はなぜあなたはまだそれなしでこのエラーを取得する理由を言うことはできません。 – estus