简体   繁体   中英

Angular 2 AND Karma Test AND Async HTTP

so my problem is very easy to explain

this is my test spec

import {
  describe,
  expect,
  it,
  inject,
  beforeEachProviders
} from 'angular2/testing_internal';
import {RestClient} from './rest.service';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/delay';
import {
  HTTP_PROVIDERS
} from 'angular2/http';
export function main() {
   describe('RestClient Service', () => {
      beforeEachProviders( () => [HTTP_PROVIDERS, RestClient] );
      it('is defined', inject( [RestClient], (client) =>{
         client.get('http://jsonplaceholder.typicode.com/posts/1')
         .delay(2000)
         .toPromise()
         .then((res) => {
            console.log('test');
            expect(res.length).toBeGreaterThan(1000);
         });
       }));
    });
  }

and this is the method in the "RestClient" class that return an Observable

public get(url:string): Observable<any> {
    return this.http.get(url).map(res => res.json());
}

So, i start the test and the test return

START:
LOG: 'ciao'
RestClient Service
    ✔ is defined
PhantomJS 2.0.0 (Mac OS X 0.0.0) LOG: 'ciao'

Finished in 0.026 secs / 0.038 secs

SUMMARY:
   ✔ 2 tests completed

For Karma all work well and the test is passed correctly and is not true, and at the same time if i put a console.log into the "then" never is called. Som i suppose that is a problem with Async calls, do you have any idea howto test in Angular2 Async Calls i have used Inject and AsyncInject too. I know that i can use a MockBackend but i need to test with external urls

thanks in advance for your help

injectAsync should solve your problem, but you need to return the promise:

it('is defined', injectAsync( [RestClient], (client) =>{
  return client.get('http://jsonplaceholder.typicode.com/posts/1')
  .delay(2000)
  .toPromise()
  .then((res) => {
     console.log('test');
     expect(res.length).toBeGreaterThan(1000);
  });
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM