Angular5 / ng测试错误:TypeError:this.handler.handle不是函数

时间:2018-03-08 07:33:50

标签: angular testing

这是我的Angular配置:

Angular CLI: 1.7.2
Node: 6.10.0
OS: win32 x64
Angular: 5.2.5
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

@angular/cli: 1.7.2
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.1
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.6.2
webpack: 3.11.0

我的package.json文件:

{
  "name": "xxxx",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "ng2ninja": "ng2ninja"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "5.2.5",
    "@angular/common": "5.2.5",
    "@angular/compiler": "5.2.5",
    "@angular/core": "5.2.5",
    "@angular/forms": "5.2.5",
    "@angular/platform-browser": "5.2.5",
    "@angular/platform-browser-dynamic": "5.2.5",
    "@angular/router": "5.2.5",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0",
    "bootstrap": "4.0.0",
    "core-js": "2.4.1",
    "font-awesome": "4.7.0",
    "rxjs": "5.5.6",
    "tslint-sonarts": "^1.6.0",
    "yarn": "^1.5.1",
    "zone.js": "0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "^1.7.1",
    "@angular/compiler-cli": "5.2.5",
    "@angular/language-service": "5.2.5",
    "@types/jasmine": "2.8.6",
    "@types/jasminewd2": "2.0.3",
    "@types/node": "8.5.2",
    "@ng-bootstrap/ng-bootstrap": "1.0.0",
    "angular-ide": "^0.9.39",
    "codelyzer": "4.1.0",
    "jasmine-core": "2.8.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "2.0.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-coverage-istanbul-reporter": "1.3.3",
    "karma-firefox-launcher": "1.1.0",
    "karma-jasmine": "1.1.1",
    "karma-jasmine-html-reporter": "0.2.2",
    "karma-json-reporter": "1.2.1",
    "ng2ninja": "1.0.17",
    "protractor": "5.2.2",
    "ts-node": "4.1.0",
    "tslint": "5.9.1",
    "typescript": "2.6.2"
  }
}

当我运行命令' ng test' 时,我收到此错误消息:

 TypeError: this.handler.handle is not a function
            at MergeMapSubscriber.__WEBPACK_IMPORTED_MODULE_2_rxjs_operator_concatMap__.a.call [as project] node_modules/@angular/common/esm2015/http.js:1174:28)
            at MergeMapSubscriber._tryNext node_modules/rxjs/_esm2015/operators/mergeMap.js:109:1)
            at MergeMapSubscriber._next node_modules/rxjs/_esm2015/operators/mergeMap.js:99:1)
            at MergeMapSubscriber.next node_modules/rxjs/_esm2015/Subscriber.js:83:1)
            at ScalarObservable._subscribe node_modules/rxjs/_esm2015/observable/ScalarObservable.js:42:1)
            at ScalarObservable._trySubscribe node_modules/rxjs/_esm2015/Observable.js:171:1)
            at ScalarObservable.subscribe node_modules/rxjs/_esm2015/Observable.js:159:1)
            at MergeMapOperator.call node_modules/rxjs/_esm2015/operators/mergeMap.js:78:1)
            at Observable.subscribe node_modules/rxjs/_esm2015/Observable.js:156:1)

这是我的测试:

import {TestBed, inject} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {UserService} from './user.service';
import {environment} from '../environments/environment';
import {JwtInterceptorService} from './jwt-interceptor.service';
import {User} from './services/model/user';
import {HttpClient, HttpHandler} from '@angular/common/http';
...
     it('should authenticate a user', () => {
        // spy on the store method
        spyOn(userService, 'storeLoggedInUser');

        const credentials = {login: 'toto', password: 'titi'};
        let actualUser;
        userService.login(credentials).subscribe(fetchedUser => actualUser = fetchedUser);
    ...
      });

分析和调试后,问题来自" login"用户服务的方法。

浏览了大量帖子(和解决方案)后,我不明白我的错误信息的真正来源。

这是我的用户服务:

 login(credentials): Observable<User> {
    var headers = new HttpHeaders();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    var paramCredentials = "grant_type=password"
      + "&credentials=true"
      + "&scope=read write"
      + "&accept=application/json"
      + "&username=" + credentials.username
      + "&password=" + credentials.password;

    return this.http.post<User>(`${environment.oAuthUrl}/oauth/token`, paramCredentials, {headers: headers}).pipe(
      tap(user => this.storeLoggedInUser(user))
    );
  }

 storeLoggedInUser(user) {
    window.localStorage.setItem('jwtToken', JSON.stringify(user));
    this.jwtInterceptorService.setJwtToken(user.token);
  }

有什么想法吗?

感谢您提前

4 个答案:

答案 0 :(得分:8)

请在您调用它的component.ts中添加错误处理程序 登录(凭证)方法。

user_login() {
this.userService.login(credentials).subscribe((res) => {
console.log(res);
}, (error) => {
console.log(error);
});

答案 1 :(得分:3)

对我来说,此问题来自尝试像这样在我的提供程序中包含HttpClientHttpHandler

providers: [
    HttpClient,
    HttpHandler
]

这总是沿着_TypeError: this.handle.handler is not a function

抛出错误

要解决此问题,我发现我可以从提供程序中删除HttpClientHttpHandler,而是像这样将HttpClientTestingModule添加到我的导入文件中:

imports: [
    HttpClientTestingModule
]

这在我针对Angular 7的Karma单元测试中为我解决了这个特殊错误。

答案 2 :(得分:1)

我在尝试将测试转换为使用HttpTestingController时遇到了这个问题。我相信已接受的答案只会解决问题并将其打印到控制台。对于下面的解决方案,我仍然有很多地方仍然无法理解,但是希望它可以对某人有所帮助。

应用程序中的问题是我在HttpHandler列表中提供了providers。这导致_this.handler成为堆栈跟踪中HttpHandler中有问题的行上的http.js

var /** @type {?} */ events$ = concatMap.call(of(req), function (req) { return _this.handler.handle(req); });

我从HttpHandler的提供者中删除了TestBed.configureTestModule,然后_this.handler是一个具有适当HttpInterceptorHandler功能的handle

答案 3 :(得分:0)

可能您未使用HttpHandler,但是Angular无法找到它。

尝试从app.module.ts中的“导入”和“提供程序”中删除HttpHandler:

import {HttpClient} from '@angular/common/http';
...
providers: [HttpClient],