我正在尝试调用 fail
我的片段中的条件。
但是当我使用 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]);
}));
请让我知道我做错了什么
最佳答案
你需要包装你知道会失败的函数,然后 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
中测试(或监视)其他内容时你可以在你的测试中做到这一点: try {
call();
} catch (error) {
expect(MySpy).to.have.been.calledWith(error);
}
关于angularjs - 如何在 Sinon JS 的单元测试中处理 sinon.stub().throws(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39387822/