在我的Angular 2.0.0应用中,我试图在使用AuthHttp
而不是Http
的服务中模拟HTTP调用。
@Injectable()
export class FundingPlanService {
constructor(private http: AuthHttp);
getFundingPlans(): Observable<FundingPlan[]> {
return this.http.get('http://localhost:8080/api/fundingplans')
.map((response: Response) => {
return response.json();
}).map((json: any) => {
// some logic here
return fundingPlans;
});
}
}
在测试中,我在网上找到了这里和那里发现的碎片,如下:
describe('Service: FundingPlan', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
FundingPlanService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, options) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
},
{
provide: AuthHttp,
useFactory: (http) => new AuthHttp(new AuthConfig(), http),
deps: [Http]
}
]
});
});
it('should ...', inject([FundingPlanService, MockBackend], fakeAsync((service: FundingPlanService, backend: MockBackend) => {
backend.connections.subscribe((connection: MockConnection) => {
expect(false).toBe(true);
expect(connection.request.method).toBe(RequestMethod.Get);
expect(connection.request.url).toBe('http://localhost:8080/api/fundingplans');
});
let fundingPlans = service.getFundingPlans();
})));
});
Http
使用MockBackend
,AuthHttp
使用带有模拟后端的Http
:
LOG: '*** const ', AuthHttp{http: Http{_backend: MockBackend{connectionsArray: ...
但expect
语句永远不会执行。可以肯定的是,我添加了expect(false).toBe(true);
但测试已完成SUCCESS
。
我错过了什么?
答案 0 :(得分:0)
您错过了请求的异步行为,有多种方法可以实现异步测试:
将测试包装在async
区域中:
it('should ...', async(inject([FundingPlanService, MockBackend], (service: FundingPlanService, backend: MockBackend) => {
...
...
}));
使用done()
回调参数:
it('should ...', (done) => {inject([FundingPlanService, MockBackend], (service: FundingPlanService, backend: MockBackend) => {
...
...
done();
}});
您使用的是fakeAsync
,但这是针对假异步定时器的,在这里您明确使用异步调用,因此您应该使用这两种方法中的一种。
您正在订阅从未调用的连接后端,因为您从不调用http
,订阅连接后端应该用于指定您希望在模型中获得哪个响应:
it('should ...', async(inject([FundingPlanService, MockBackend], (service: FundingPlanService, backend: MockBackend) => {
backend.connections.subscribe((connection: MockConnection) => {
const options: ResponseOptions = new ResponseOptions(
{
body : "Your body as string",
headers: new Headers(),
status : 200
}
);
conn.mockRespond(new Response(options));
});
//And then your expectations
expect(service.getFundingPlans()).toBe(dunnoWhat);
}));