Нет поставщика для $ инжектора в Angular Testing - PullRequest
0 голосов
/ 12 февраля 2019

Я пытался настроить тестирование в нашем приложении Hybrid AngularJS / NG6, но это сложно сделать.Я постоянно получаю постоянные ошибки.Последним является следующее:

Ошибка: StaticInjectorError (DynamicTestModule) [$ инжектор]:

StaticInjectorError (Платформа: ядро) [$ инжектор]:

NullInjectorError: Нет поставщика для $ инжектора!

У меня есть следующее component:

import { Component, OnInit, Input, Inject } from '@angular/core';
import { DashboardService } from '../../services/dashboard/dashboard.service';

@Component({
    templateUrl: './views/components/dashboard/dashboard.component.html'
})
export class DashboardComponent implements OnInit {
    @Input()
    Session;
    Util;
    constructor(
        private _dashboardService: DashboardService,
        @Inject('Session') Session: any,
        @Inject('Util') Util: any
    ) {
        this.Session = Session;
        this.Util = Util;
    }

    ngOnInit() {
        this._dashboardService
            .getPrograms(this.Session.user.organization)
            .subscribe(
                data => {
                    console.log(data);
                },
                error => {
                    console.log(error);
                }
            );
    }
}

Это прекрасно работает.Я могу получить данные из нашего API.С другой стороны, у меня есть файл spec:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

import { DashboardComponent } from './dashboard.component';
import { DebugElement } from '@angular/core';

import { DashboardService } from '../../services/dashboard/dashboard.service';
import { ApiService } from '../../services/api.service';

import { HttpClientModule } from '@angular/common/http';

describe('The Dashboard', () => {
    let component: DashboardComponent;
    let fixture: ComponentFixture<DashboardComponent>;
    let de: DebugElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
                CommonModule,
                FormsModule,
                ReactiveFormsModule,
                HttpClientModule
            ],
            declarations: [DashboardComponent],
            providers: [
                {
                    provide: 'Util',
                    useFactory: ($injector: any) => $injector.get('Util'),
                    deps: ['$injector']
                },
                {
                    provide: 'Session',
                    useFactory: ($injector: any) => $injector.get('Session'),
                    deps: ['$injector']
                },
                DashboardService,
                ApiService            
            ]
        })
            .overrideComponent(DashboardComponent, {
                set: {
                    templateUrl:
                        '/dist/views/components/dashboard/dashboard.component.html'
                }
            })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(DashboardComponent);
        component = fixture.componentInstance;
        de = fixture.debugElement;
        fixture.detectChanges();
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });
});

Когда я запускаю этот файл spec, я получаю сообщение об ошибке, указанное выше.Я понятия не имею, что пытается сообщить мне ошибка, поскольку она очень расплывчатая.

Как правильно указать модуль $Injector в файле spec?

1 Ответ

0 голосов
/ 12 февраля 2019

Я также пытался протестировать детали Angular в моем гибридном приложении с зависимостями от AngularJS, но мне это не удалось.Тестировать либо часть AngularJS с зависимостями Angular, либо часть Angular с зависимостями AngularJS внутри гибрида очень сложно.Я нашел два возможных решения из этого сообщения на GitHub- Полностью издеваться над деталями из других рамок.- Создавайте мини-приложения, которые содержат все зависимости из другого фреймворка.

...