【问题标题】:how to handle sinon.stub().throws() in unit test by Sinon JSSinon JS 如何在单元测试中处理 sinon.stub().throws()
【发布时间】:2017-01-16 04:51:40
【问题描述】:

我试图在我的 sn-p 中调用 fail 条件。 但是当我使用sinon.stub().throws() 方法时,它会显示错误。 我无法在代码中处理它。 这是我的 sn-p:

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);
    });
}

**这是我的单元测试sn-p:**

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]);

  }));

请告诉我做错了什么

【问题讨论】:

    标签: angularjs unit-testing ecmascript-6 sinon chai


    【解决方案1】:

    你需要包装你知道会失败的函数,然后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);
      }
    

    【讨论】:

      【解决方案2】:

      这个问题在这个答案之前已经一个月了,但我遇到了类似的错误,谷歌没有对这种行为做出任何解释。我也想测试我的登录失败分支,stub.throws() 实际上 threw 错误(导致测试失败)而不是拒绝登录承诺。如果有人知道为什么会发生这种情况,我将不胜感激。

      无论如何,这对我有用:

      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
      

      【讨论】:

      • 在 mock 上的 throws 和 Promises 有类似的问题。我假设 API 是相同的。尝试使用 rejects 而不是存根中的 throws
      猜你喜欢
      • 2017-02-06
      • 2020-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 2018-05-30
      • 2020-05-04
      • 1970-01-01
      相关资源
      最近更新 更多