单元测试由使用angular2-jwt AuthHttp调用而不是http调用的服务注入的组件

时间:2017-03-09 09:44:40

标签: unit-testing angular typescript angular2-jwt

我一直用HTTP来调用API来做我的东西,后来介绍了angular2-jwt来拦截http调用并传递jwt tockens。在使用AuthHttp之前,单元测试工作正常。我创建了'mockuserdata'模型来返回模拟值

在我添加http和AuthHttp的提供程序之前失败的每个单元测试用例如下

0x4004e2

介绍上面的提供者 后应该实例化UsersComponent '但是' 它检查loadUserList()是绑定数据源 '失败

/ *用户运营服务* /

    {provide: Http, useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => 
    { return new Http(backendInstance, defaultOptions);},
       deps: [MockBackend, BaseRequestOptions] },
 { provide: AuthHttp, useExisting: Http, deps: [Http] }

/ *用户列表组件* /

import {Headers,RequestOptionsArgs,Response,URLSearchParams, RequestMethod,RequestOptions }from '@angular/http';
import { Injectable, Optional }from '@angular/core';
import { Observable}from 'rxjs/Observable';
import * as models from '../models';
import { AuthHttp }from 'angular2-jwt';
import 'rxjs/Rx';

 @ Injectable()
export class UserOperationsApi {
    protected basePath = '/api';
    public defaultHeaders: Headers = new Headers();
    constructor(protected http: AuthHttp,  @ Optional()basePath: string) {
        if (basePath) {
            this.basePath = basePath;
        }
    }
/**
     * Returns all users
     * Returns list of all users
     */
    public getAllUsers(extraHttpRequestParams ?  : any): Observable < Array < models.User >> {
        const path = this.basePath + '/users';
        let queryParameters = new URLSearchParams();
        let headerParams = this.defaultHeaders;
        let requestOptions: RequestOptionsArgs = {
            method: 'GET',
            headers: headerParams,
            search: queryParameters
        };

        return this.http.request(path, requestOptions)
        .map((response: Response) => {
            if (response.status === 204) {
                return undefined;
            } else {
                return response.json();
            }
        });
    }
}

** *用户组件单元测试** ** **

import {Component,OnInit}from '@angular/core';
import {Router } from '@angular/router';
import {UserOperationsApi }from '../services';
import {DialogService }from '../services';
import { Subscription }from 'rxjs';
 @ Component({
    selector: 'my-app',
    templateUrl: './list-users.component.html',
    providers: [UserOperationsApi]
})
export class UsersComponent implements OnInit {
    public userData: any;
    constructor(private api: UserOperationsApi, private router: Router) {
        this.loadUserList();
    }
    // loading user list
    loadUserList() {
        // To get data from api
        this.busy = this.api.getAllUsers()
            .subscribe(
                data => this.handleConfiguredUsers(data),
                error => {
                throw ({
                    message: 'Error occured! while retreiving data from server.'
                });
            });
    }
    // users list to be loaded
    handleConfiguredUsers(data) {
        this.userData = data;
    }
}

1)单元测试返回空值有什么问题。

1 个答案:

答案 0 :(得分:1)

以下对我有用。指示使用Http而不是使用

的AuthHttp

{provide:AuthHttp,useExisting:Http}

所以我的单元测试文件有以下变化。

describe('list-users.component.ts', () => {
beforeEach(() => {
        TestBed.configureTestingModule(
            {
                declarations: [UsersComponent],
                imports: [HttpModule, DevExtremeModule],
                providers: [MockBackend, BaseRequestOptions,
                    { provide: XHRBackend, useClass: MockBackend },
                    { provide: Router, useClass: MockRouter },
                    { provide: ActivatedRoute, useClass: MockRouter },
                    { provide: AuthHttp, useExisting: Http }
                ]
            });
    });

希望有一天对某人有用,干杯:)