测试angular2 http服务

时间:2017-06-11 08:44:29

标签: angular angular2-services angular2-testing

我开始学习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


        }
)));

我为这么简单的请求道歉,但我经历的大部分指南已经过时了

1 个答案:

答案 0 :(得分:0)

阅读@ 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()
            }
        )

    } )

} );