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

The*_*nic 3 unit-testing sinon angularjs chai ecmascript-6

我试图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);
    });
}
Run Code Online (Sandbox Code Playgroud)

**这是我的单元测试片段:**

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

  }));
Run Code Online (Sandbox Code Playgroud)

请让我知道我做错了什么

cha*_*deb 9

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

在测试(或监视)其他内容时,methodThatCallsAnotherFailingMethod您可以在测试中执行以下操作:

  try {
    call();
   } catch (error) {
    expect(MySpy).to.have.been.calledWith(error);
  }
Run Code Online (Sandbox Code Playgroud)


Cez*_*e07 0

这个问题距此答案已有一个月了,但我遇到了类似的错误,并且谷歌尚未对此行为提供任何解释。我也想测试我的登录的失败分支,并且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
Run Code Online (Sandbox Code Playgroud)

  • 在模拟上的 throws 和 Promises 也有类似的问题。我假设 API 是相同的。尝试在存根中使用“rejects”而不是“throws”。 (3认同)