在我的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使用带有mocked后端的Http:
LOG: '*** const ', AuthHttp{http: Http{_backend: MockBackend{connectionsArray: ...但是expect语句永远不会执行。只是为了确认一下,我已经添加了expect(false).toBe(true);,但是使用SUCCESS完成了测试。
我遗漏了什么?
发布于 2016-10-13 22:00:06
第一个问题:
你错过了你的请求的异步行为,有多种方法可以实现异步测试:
通过将测试包装在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);
}));https://stackoverflow.com/questions/40018332
复制相似问题