angularjs - 如何在 Sinon JS 的单元测试中处理 sinon.stub().throws()

标签 angularjs unit-testing ecmascript-6 sinon chai

我正在尝试调用 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/

相关文章:

javascript - AngularJS:超时结束后执行函数

java - 如何测试依赖于 SoftReference 的代码?

javascript - 为什么这两种进行异步调用的方法(一种使用 Promise,另一种使用生成器)不会产生相同的结果?

javascript - TypeError : obj[key]. 包括不是一个函数:在过滤器函数中

javascript - 如何导入已经导入另一个文件的文件?

javascript - 使用 Angularjs 单击按钮在另一个选项卡上打开 html

Javascript 对象未使用 Angular js 在 View 中更新

java - 当您同时具有虚拟和真实实现的接口(interface)时,单元测试的最佳方法是什么?

c# - XUnit 如何模拟 IMemoryCache ASP.NET Core

angularjs - Ionic - 单击后退按钮时重新加载并在 ng-repeat 中显示新数据