gpt4 book ai didi

javascript - 如何在 Angular2 中对 Http get MockBackend 进行单元测试?

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:03 26 4
gpt4 key购买 nike

如何在Angular2中对Http get MockBackend进行单元测试?

我在测试我的 http 单元测试时遇到问题。每次我查看 MockBackend 时,它似乎都令人困惑,很多代码和一些导入永远无法工作。

我只想要一个非常基本的 http get 单元测试

我正在使用:typescript、angular2、jasmine 和 karma runner。

我的实际代码工作正常。

这是我正在测试的代码:

 import {Injectable} from 'angular2/angular2';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';

@Injectable()

export class FirebaseService{
headers: Headers;

//Test issue seems to be here when I inject Http instance.
constructor(public http?: Http) {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
}

//This is the method I'm testing.
public getSpotifyTracks = ():Promise<Object> =>{
return this.http
.get('https://api.spotify.com/v1/tracks/0eGsygTp906u18L0Oimnem', {headers:this.headers})
.map((response) => {
return response.json()
}).toPromise();
}

}

这是我对该代码的单元测试:

import {it, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick} from 'angular2/testing';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {FirebaseService} from '../app/firebase-service';

describe('Firebase Service Calls', () => {
beforeEachProviders(()=> [Http, FirebaseService]);

//Issue seems to be here????
it('get all tracks from spotify', injectAsync([FirebaseService],(service) => {

return service.getSpotifyTracks().then((response) => {
expect(response.length).not.toBe(null);
});

}), 3000);

});

最佳答案

首先导入所有模块:

import {it,describe,expect,inject,injectAsync,beforeEachProviders} from 'angular2/testing';
import {provide, Injector} from 'angular2/core';

import {MockBackend} from 'angular2/http/testing';
import {YourServiceToBeTested} from 'path/to/YourServiceToBeTested';

接下来您需要声明 Mocked HttpBackend :

describe('Service with Http injected', () => {
beforeEachProviders(() => {
[
MockBackend,
BaseRequestOptions,
provide(
Http,
{
useFactory: (backend, defaultOptions) => {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
}),
YourServiceToBeTested
]
});

最后,在每个测试中,您需要注入(inject)模拟并设置模拟值(即您的服务为该特定测试返回的虚假数据)

it('should respect your expectation',

inject(
[YourServiceToBeTested, MockBackend],
(yourServiceToBeTested, mockBackend) => {

let response = 'Expected Response from HTTP service usually JSON format';
let responseOptions = new ResponseOptions({body: response});
mock.connections.subscribe(
c => c.mockRespond(new Response(responseOptions)));

var res = yourServiceToBeTested.ServiceMethodToBeTest(serviceParams);
expect(res).toEqual('your own expectation');
}));

关于javascript - 如何在 Angular2 中对 Http get MockBackend 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34162666/

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