Angular Testing of GET request that requires an Authentication Service

Viewed 1928

I am new to Karma/Jasmine testing and I'm attempting to set up a test for my service which performs a GET request. I'm using the XHRBackend with a MockBackend object to simulate fake requests and responses. I have a 'webService' which is the one performing the GET and an 'authService' which holds the connection string and the access token. I've set this test up as follows:

describe('WebService Tests', () => {

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [HttpModule],
            providers: [
                AuthService,
                AdalService,
                WebServicesService,
                { provide: XHRBackend, useClass: MockBackend }
            ]
        })
        .compileComponents();
    }));

beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => {
            backend = be;
            authService = new AuthService(new AdalService(), http);
            webService = new WebServicesService(http, authService);
            fakeWebServicesData = makeServicesData;
            let webOptions = new ResponseOptions({status: 200, body: {data: fakeWebServicesData}})
            webResponse = new Response(webOptions);
        }));

        it('should have expected successful GET of WebServices', async(inject([], () => {
            backend.connections.subscribe((c: MockConnection) => c.mockRespond(webResponse));

            webService.getWebServices().toPromise()
            .then(data => {
                expect(data.length).toBe(fakeWebServicesData.length,
                'should have received all web services data');
            })

        })))

The response I receive is of a failure because data.length is undefined, and it was expected to be 1 (the fake data I'm using is of length 1). I'm a bit unsure as to why this is happening. The method it is calling is as follows:

getWebServices(): Observable<WebService[]> {
        let connection = this.authService.connection + '/services';
        // Add authorization header with jwt token
        let token = this.authService.getToken();
        let headers = new Headers({ 'Authorization': 'Bearer ' + token });
        let options = new RequestOptions({ headers: headers });

        // Get services from web service api endpoint
        return this.http.get(connection, options)
            .map((response: Response) => response.json())
            .catch((error: Response) => {
                return Observable.throw(error);
            });
    }

My suspicion is that because I haven't yet logged in with the AuthService before I make the mock request, that maybe it returns undefined. Do I need to login with my authService before setting up this mock request? (e.g. do a mock login prior?) If so, how do I perform two mock requests in a row within the same test? Or is there a different way to fake the authentication? Any help would be appreciated. Thanks so much.

UPDATE: This is my fake data

const makeServicesData = [
    { 
        name: "service1", version: "1.0.0", versionPublishedBy: "",
        creationTime: "", snapshotId: "", runtimeType: "",
        initCode: "", code: "", description: "", operationId: "",
        inputParameterDefinitions: [
            { name: "", type: "" }
        ],
        outputParameterDefinitions: [
            { name: "", type: "" }
        ],
        outputFileNames: [""],
        myPermissionOnService: "read/write"
    }
]
1 Answers
Related