Angular,Jasmine:单元测试中的错误(引发表达式)

时间:2018-07-08 08:07:46

标签: angular jasmine karma-jasmine karma-webpack

我想测试我的authService类,这里有这样的方法,但是我在单元测试中总是出错。我看了很多页面,但没有任何想法。

login(user) {
this.http.post(this.baseUrl + '/api/Token', user).subscribe((result: any) => {
  localStorage.setItem(this.tokenKey, result.token);
  this.setTokenEmail(result.token);
  this.router.navigateByUrl('/');
},
  (error => {
    throw error;
  })
);

}

单元测试:

it('should throw error when user unothorized', () => {
  const mockErrorResponse = {
    status: 403, statusText: 'Bad Request'
  };

  service.login(user);
  expect(service.login).toThrow();

  expect(httpMock
    .expectOne(environment.baseUrl + '/api/Token')
    .flush("User unothorized", mockErrorResponse)).toThrow()

});

错误:

    HttpErrorResponse: Http failure response for http://localhost:9575/api/Token: 403 Bad Request in http://localhost:9876/_karma_webpack_/main.bundle.js (line 610)
    http://localhost:9876/_karma_webpack_/main.bundle.js:610:31760
    __tryOrUnsub@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105425:20
    error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105384:38
    _error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105316:31
    error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105290:24
    _error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105316:31
    error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105290:24
    _error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105316:31
    error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105290:24
    notifyError@http://localhost:9876/_karma_webpack_/vendor.bundle.js:104745:31
    _error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:104232:32
    error@http://localhost:9876/_karma_webpack_/vendor.bundle.js:105290:24
    flush@http://localhost:9876/_karma_webpack_/vendor.bundle.js:11281:32
    http://localhost:9876/_karma_webpack_/main.bundle.js:577:23
    invoke@http://localhost:9876/_karma_webpack_/polyfills.bundle.js:5766:31
    onInvoke@http://localhost:9876/_karma_webpack_/vendor.bundle.js:146120:45

当我删除抛出错误表达式时,测试通过。我需要这个,因为我使用自己的错误处理程序。我怎样才能解决这个问题?

0 个答案:

没有答案