2016-09-08 1 views
0

내 코드에서 fail 조건을 호출하려고합니다. 그러나 sinon.stub().throws() 메서드를 사용하면 오류가 발생합니다. 코드에서 처리 할 수 ​​없습니다. **Sinon JS 단위 테스트에서 sinon.stub(). throws()를 처리하는 방법

login() { 
    let loginData = this.loginData; 
    return this.authService.login(loginData).then(userData => { 

     let msg = `${this.niceToSeeYouAgain} ${userData.email}!`; 
     this.userAlertsService.showSuccessToast(msg); 
     this.navigationService.afterLoggedIn(); 

     //above lines are covered in test cases 

    }, errorInfo => { 
     // below line are needed to test 
     this.userAlertsService.showAlertToast(errorInfo); 
    }); 
} 

그리고 여기 내 단위 테스트 조각입니다 : 여기 내 조각이다

it('.login() - should throw exception - in failure case', sinon.test(() => { 

    let errorInfo = "some error"; 

    let stub = sinon.stub(authService, 'login').throws(); 

    let spy1 = sinon.spy(controller.userAlertsService, 'showAlertToast'); 


    //call function 
    controller.login(); 
    // $timeout.flush(); 

    // expect things 
    console.log(stub.callCount, stub.args[0]); 

    })); 

날이 질문은 잘못된

답변

0

뭐하는 거지 알려 주시기 바랍니다 ** 한 달이 지났지 만 비슷한 오류가 발생했습니다. Google에서는이 동작에 대해 설명하지 않았습니다. 내 로그인의 실패 지점을 테스트하고 싶었고 stub.throws() 실제로 은 로그인 약속을 거부하는 대신 오류 (테스트 실패 원인)를 던졌습니다. 왜 이런 일이 일어 났는지 아는 사람이라면 고맙겠습니다.

let d = Q.defer();   // Or whichever promise library you use 
d.reject();     // Force the promise to fail 
let stub = sinon.stub(authService, 'login').returns(d.promise); // Should do what you want 
// The rest of the test 
+0

비슷한 문제가 있었다은 동일합니다 . 스텁에서'throws' 대신'rejects'를 사용해보십시오. –

0

당신은 당신이 실패 할 것입니다 알고있는 기능을 포장해야하고, 다음 call 그것 : 어떤 경우에

, 이것은 나를 위해 일한 것입니다. 예 :

it('handles errors in methodThatCallsAnotherFailingMethod', function() { 
    error = new Error("some fake error"); 
    sandbox.stub(SomeObject, "doSomething").throws(error); 

    call = function() { 
    // methodThatCallsAnotherFailingMethod calls SomeObject.doSomething() 
    methodThatCallsAnotherFailingMethod(); 
    }; 

    expect(call).to.throw(Error); 

});

테스트 (또는 감시) 당신이 당신의 시험에서이 작업을 수행 할 수 있습니다 methodThatCallsAnotherFailingMethod 다른 물건을 : 던져 API를 가정 할 mock.I'm에 약속

try { 
    call(); 
    } catch (error) { 
    expect(MySpy).to.have.been.calledWith(error); 
    }