单元测试由使用Angular2-JWT Authhttp调用而不是HTTP调用的服务注入的组件



我一直在使用HTTP来调用API来做我的工作,后来引入了Angular2-JWT来拦截HTTP调用并传递JWT Tockens。单位测试工作正常,直到使用AuthHTTP。我创建了" MockuserData"模型来返回模拟值

每个单位测试用例失败,直到我添加HTTP和AUTHHTTP的提供商如下

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

介绍上述提供者的应实例化用户component '获得了传递,但是'它检查loaduserlist()正在绑定datasource strong>'失败

/*用户操作服务*/

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

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

import {async,TestBed,inject}from '@angular/core/testing';
import {Response,ResponseOptions, XHRBackend } from '@angular/http';
import {    MockBackend,    MockConnection}from '@angular/http/testing';
import {    HttpModule}from '@angular/http';
import {    Router, ActivatedRoute}from '@angular/router';
import {    MockRouter}from '../mock/router.mock';
import {    usersData}from '../data/mockData/users';
import {    UsersComponent}from './list-users.component';
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: Http, useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
                            return new Http(backendInstance, defaultOptions);
                        },
                        deps: [MockBackend, BaseRequestOptions]
                    },
                    { provide: AuthHttp, useExisting: Http, deps: [Http] }
                ]
            });
    });
    it('should instantiate UsersComponent', () => {
        const fixture = TestBed.createComponent(UsersComponent);
        let compInstance: UsersComponent = fixture.componentInstance;
        expect(compInstance instanceof UsersComponent).toBe(true, 'should create UsersComponent');
    });
    it('It checks loadUserList() is binding datasource',
        async(inject([XHRBackend],
                (mockBackend: MockBackend) => {
                mockBackend.connections.subscribe(
                    (connection: MockConnection) => {
                    connection.mockRespond(new Response(
                            new ResponseOptions({
                                body: usersData
                            })));
                });
                const fixture = TestBed.createComponent(UsersComponent);
                let instance: UsersComponent = fixture.componentInstance;
                instance.instance.loadUserList();;
                expect(instance.userData.length).toEqual(usersData.length);
                expect(instance.userData).toBe(usersData);
            })));
}

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

以下对我有用。指示使用

使用http而不是authhttp

{提供: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 }
                ]
            });
    });

希望有一天对某人有用,欢呼:)

相关内容

  • 没有找到相关文章

最新更新