jeudi 7 décembre 2017

Angular 5 testing code in module constructor

I'm trying to test code that's in one of my module's constructor. Basically, the module (named GraphqlModule) configures a service (named Graphql) and provides it. The configuration happens in the module's constructor.

Here's the code I use to test the module.

it('should use the GraphqlConfigs and ServerConfigs', (done: DoneFn) => {

    // Adding spies to Config classes
    let serverConfigs = new ServerConfigs();
    let serverDomainSpy = spyOnProperty(serverConfigs, 'ServerDomain', 'get').and.callThrough();
    let serverPortSpy = spyOnProperty(serverConfigs, 'ServerPort', 'get').and.callThrough();

    let gqlConfigs = new GraphqlConfigs();
    let protocolSpy = spyOnProperty(gqlConfigs, 'EndpointProtocol', 'get').and.callThrough();
    let endpointNameSpy = spyOnProperty(gqlConfigs, 'EndpointName', 'get').and.callThrough();

    TestBed.configureTestingModule({
        imports: [ GraphqlModule ],
        providers: [
            {provide: ServerConfigs, useValue: serverConfigs}, // Replacing real config classes with the ones spied on.
            {provide: GraphqlConfigs, useValue: gqlConfigs}
        ]

    }).compileComponents().then(() => {

        // This line seems to make Angular instantiate GraphqlModule
        const graphql = TestBed.get(Graphql) as Graphql;

        expect(serverDomainSpy.calls.count()).toBe(1, 'ServerConfigs.ServerDomain was not used.');
        expect(serverPortSpy.calls.count()).toBe(1,  'ServerConfigs.ServerPort was not used.');

        expect(protocolSpy.calls.count()).toBe(1, 'GraphqlConfigs.EndpointProtocol was not used.');
        expect(endpointNameSpy.calls.count()).toBe(1,  'GraphqlConfigs.EndpointName was not used.');

        done();
    });
});

As is, the test passes and works, but if I dont use the following (useless) line const graphql = TestBed.get(Graphql) as Graphql; the GraphqlModule gets instantiated after the test has been executed, which makes the test fail.

Since it's GraphqlModule that provides the Graphql service, I understand that there's some lazy loading algorithm in Angular that's triggered when I do TestBed.get(Graphql). That's fine... my question is, is there a way to make my module load in a more explicit way?

Aucun commentaire:

Enregistrer un commentaire