gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:29:39 26 4
gpt4 key购买 nike

我一直在使用 HTTP 调用 API 来做我的事情,后来引入了 angular2-jwt 来拦截 http 调用并传递 jwt token 。在使用 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] }

在引入上述提供程序后,“应该实例化 UsersComponent”通过了,但是“它检查 loadUserList() 是否绑定(bind)数据源' is failing

/* 用户操作服务*/

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

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

关于unit-testing - 单元测试由使用 angular2-jwt AuthHttp 调用而不是 http 调用的服务注入(inject)的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42691819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com