2016-05-25 7 views
1

私たちはテストライブラリのためにモカ、チャイ、シロンに移動しました。ジャスミンから来て、私は約束のテスト方法についてちょっと混乱しています。

私はフォームがサービスを呼び出し、戻り時に、それが正しい状態にユーザーをナビゲートする機能を提出する必要があり:

submit(event, theForm){ 
    event.preventDefault(); 

    if(theForm.$valid){ 
     this.AuthenticationService.authenticateUser({ 
      email: this.email, 
      password: this.password 
     }).then((result) => { 
      this.$state.go('dashboard.home') 
     }); 
    } 
} 

は、次の試験であり道の一部を得ている:

it('should submit the login credentials if valid', function(){ 

    var dfd = q.defer(), 
     promise = dfd.promise; 

    controller.email = '[email protected]'; 
    controller.password = 'Password123'; 

    sinon.stub(service, 'authenticateUser').returns(promise); 
    sinon.spy(state, 'go'); 
    sinon.spy(controller, 'submit'); 

    controller.submit(event, theForm); 

    dfd.resolve(); 

    expect(controller.submit).to.have.been.called; 
    expect(controller.submit).to.have.been.calledWith(event, theForm); 
    expect(event.preventDefault).to.have.been.called; 

    expect(service.authenticateUser).to.have.been.called; 
    expect(service.authenticateUser).to.have.been.calledWith({ 
     email: controller.email, 
     password: controller.password 
    }); 
    expect(state.go).to.have.been.called; 
    expect(state.go).to.have.been.calledWith('dashboard.home'); 
}); 

しかし、state.goが呼ばれるというアサーションは成立しません。テストをパスするために私は何を変えますか?

+0

Hey @ RyanP13上記の問題を解決しましたか?私も同じ問題に直面しています。コード "authenticateUser"をテストしようとすると約束します.. –

答えて

0

これは、コントローラーのthen()が実行される前にexpect()が呼び出されているタイミングの問題である可能性があります。これを修正するには、finally()ので、同様にあなたのstate.goアサーションをラップしてみてください。

it('should submit the login credentials if valid', function(){ 

    [...] 

    return promise.finally(function() { 
     expect(state.go).to.have.been.called; 
     expect(state.go).to.have.been.calledWith('dashboard.home'); 
    ); 
}); 

二つの重要な事柄はここに起こっている:

  1. finally()dfdが完全にされるまで、あなたのexpect()年代が実行されないことを保証します解決されました。
  2. finally()は、あなたがMochaテスト自体に戻るという約束を返します。これは、あなたが非同期コードを扱っていることをMochaに伝え、expect()が実行されるまでさらなるテストに移るのを防ぎます。 Mocha hereで非同期コードを処理する方法の詳細を読むことができます。
関連する問題