0

I am starting to learn angular2.

Have a service with the following implementation:

@Injectable()
export class PostsService {

    constructor(private http: Http) { }

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

}

I am attempting to test this:

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


        }
)));

I apologize, for such a simple request, but most of the guides I went through are outdated

Igor L.
  • 3,159
  • 7
  • 40
  • 61
  • What's your *question*? You don't seem to have gotten as far as actually writing a test. Have you read [the `MockBackend` docs](https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html), which give an example of its use? – jonrsharpe Jun 11 '17 at 08:55
  • I confess, I did not.. I am learning this during weekends, and hoped I would learn by writing and reading code. Gonna read now, will get back to the question – Igor L. Jun 11 '17 at 09:03
  • 1
    I wrote a blog article on Angular testing you may also find useful, in the context of a specific way of exposing the data to other components: http://blog.jonrshar.pe/2017/Apr/16/async-angular-tests.html – jonrsharpe Jun 11 '17 at 09:05
  • @jonrsharpe: Your blog post is the single best resource I came across for testing services. Great value allong with http://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html, even though I do not fully get Observables yet – Igor L. Jun 11 '17 at 10:11
  • I appreciate the feedback, thank you; I'm glad you found it useful! – jonrsharpe Jun 11 '17 at 10:16

1 Answers1

0

Read @jonrsharpe's blog: 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()
            }
        )

    } )

} );
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Igor L.
  • 3,159
  • 7
  • 40
  • 61