vendredi 29 avril 2016

Angular 2 testing - service won't inject

I'm using angular 2 and jasmine to try and test a couple of services, one service is dependent on the other. I keep getting a provider error for service.

import {Injectable}     from 'angular2/core';

@Injectable()
export class ServiceA {

constructor() {
}
}

spec for serviceA

import {it, 
describe, expect, 
beforeEach, 
beforeEachProviders, inject}
from 'angular2/testing';
import {ServiceA} from './serviceA;

describe('ServiceA Tests', () => {
let service: ServiceA;

beforeEachProviders(() => {
    return [
        ServiceA
    ]
});
beforeEach(inject([ServiceA], (l) => {
    service = l;
}));

it('Service Created', () => {
    expect(service).toBeDefined();
});

});

config class

import {OpaqueToken} from 'angular2/core';

export let APP_CONFIG = new OpaqueToken('app.config');

export interface Config {
applicationBaseUrl: string;    
}

export const CONFIG: Config = {
applicationBaseUrl: 'some value',
};

service b

import { Injectable,Inject}     from 'angular2/core';
import { Http,Response,RequestOptions,Headers} from 'angular2/http';
import {APP_CONFIG, Config,CONFIG}    from './app.config';
import {ServiceA} from './serviceA';

export interface IServiceB {
}

@Injectable()
export class ServiceB implements IServiceB {

constructor(private _http: Http,@Inject(APP_CONFIG)
private _config:Config,private serviceA: ServiceA) {

}

}

spec for service B

import {it, describe, expect, beforeEach, beforeEachProviders,
inject} from 'angular2/testing';
import {ServiceB} from './serviceB';
import {ServiceA} from './serviceA';
import {HTTP_PROVIDERS, Http, Response, RequestOptions,
Headers}   from 'angular2/http';
import {APP_CONFIG, Config, CONFIG}    from './app.config';
import {provide} from 'angular2/core';

import 'rxjs/Rx'; // Add all operators to Observable

describe('ServiceB Tests', () => {
let serviceB: ServiceB;
let appConfig: Config;
let http: Http;
let serviceA: ServiceA;
beforeEachProviders(() => {
    return [
        HTTP_PROVIDERS,
        provide(APP_CONFIG, { useValue: CONFIG }),
        ServiceA,
        ServiceB
    ]
});
beforeEach(inject([APP_CONFIG, Http, ServiceA,ServiceB], (ac, h, a,b) => {
    appConfig = ac;
    http = h;
    serviceA = a;
    service = b; // new ServiceB(http, appConfig, serviceA);
    appConfig.applicationBaseUrl = '/';

    }));

it('Http created', () => {
    expect(http).toBeDefined();
});

it('service a created', () => {
    expect(serviceA).toBeDefined();
});

it('App config created', () => {
    expect(appConfig).toBeDefined();
});

it('service B created', () => {
    expect(serviceB).toBeDefined();
});


});

Service A loads and runs fine. If I manually create ServiceB things work but if I try to inject ServiceB I get error.

Failed: No provider for ServiceA! (ServiceB-> ServiceA)

It creates ServiceA so not sure why its saying no provider.

Aucun commentaire:

Enregistrer un commentaire