测试angular2 http服务

Test angular2 http service

开始学习angular2了

具有以下实现的服务:

@Injectable()
export class PostsService {

    constructor(private http: Http) { }

    getAllPosts() {
        return this.http.get('/api/posts')
            .map(res => res.json())
    }

}

我正在尝试测试这个:

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpModule],
        providers: [
            PostsService,
            { provide: XHRBackend, useClass: MockBackend }
        ]
    })
})

it('should be exposed', inject([PostsService], (service: PostsService) => {
    expect(service).toBeTruthy()
}));

it('should use HTTP calls to obtain data results', 
    inject([PostsService],
        fakeAsync((service: PostsService) => {   
            // test some mocked response data
            // test connection
            // whatever else needs to be tested


        }
)));

对于如此简单的请求,我深表歉意,但我阅读的大部分指南都已过时

阅读@jonrsharpe 的博客:http://blog.jonrshar.pe/2017/Apr/16/async-angular-tests.html

/* tslint:disable:no-unused-variable */
import {
    Injectable,
    ReflectiveInjector
} from '@angular/core';

import {
    TestBed,
    fakeAsync,
    inject
} from '@angular/core/testing'

import { PostsService } from './posts.service'
import {
    BaseRequestOptions,
    ConnectionBackend,
    Http,
    Response,
    ResponseOptions,
    RequestMethod,
    RequestOptions,
    XHRBackend
} from '@angular/http'
import { MockConnection, MockBackend } from '@angular/http/testing'


describe('MockBackend PostsService', () => {

    beforeEach(() => {
        this.injector = ReflectiveInjector.resolveAndCreate([
            { provide: ConnectionBackend, useClass: MockBackend },
            { provide: RequestOptions, useClass: BaseRequestOptions },
            Http,
            PostsService
        ] )
        this.postsService = this.injector.get( PostsService )
        this.backend = this.injector.get( ConnectionBackend ) as MockBackend
    } )

    it( 'should be exposed', () => {
        expect( this.postsService ).toBeTruthy()
    } );

    it( 'should use HTTP calls to the api/posts URL', () => {
        this.backend.connections
            .subscribe( ( connection : any ) => this.lastConnection = connection )
        this.postsService.getAllPosts()
        expect( this.lastConnection ).toBeDefined()
        expect( this.lastConnection.request.url ).toBe( '/api/posts' )
        expect( this.lastConnection.request.method ).toEqual( RequestMethod.Get,
                                                            'Expected GET request' )
    } );

    it( 'should return some data', done => {
        let expectedResult = [
            {
                "userId": 1,
                "id": 1,
                "title": "sunt aut",
                "body": "quia et"
            },
            {
                "userId": 1,
                "id": 2,
                "title": "qui est",
                "body": "est rerum"
            }
        ]

        this.backend.connections.subscribe( ( connection : MockConnection ) => {
            connection.mockRespond( new Response( new ResponseOptions( {
                status: 200,
                body: expectedResult
            } ) ) )
        })

        this.postsService.getAllPosts()
            .subscribe( data => {
                expect( data ).toEqual( expectedResult )
                done()
            }
        )

    } )

} );