2

运行时ng test,我收到一条错误消息:

Error: Illegal state: Could not load the summary for directive AppComponent.

我不确定为什么会收到此错误,因为我正在引用和声明 AppComponent。

这是我的 app.component.spec.ts

import { ComponentFixture, TestBed } from "@angular/core/testing";
import { NO_ERRORS_SCHEMA } from "@angular/core";
import { Router } from "@angular/router";
import { ProjectService } from "../../shared/service/project/project.service";
import { AppComponent } from "./app.component";

describe("AppComponent", () => {
    let comp: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(() => {
        const routerStub = {
            navigate: () => ({})
        };
        const projectServiceStub = {
            GetActiveProject: () => ({
                name: {}
            })
        };
        TestBed.configureTestingModule({
            declarations: [ AppComponent ],
            schemas: [ NO_ERRORS_SCHEMA ],
            providers: [
                { provide: Router, useValue: routerStub },
                { provide: ProjectService, useValue: projectServiceStub }
            ]
        });
        fixture = TestBed.createComponent(AppComponent);
        comp = fixture.componentInstance;
    });

    it("can load instance", () => {
        expect(comp).toBeTruthy();
    });

    describe("ngOnInit", () => {
        it("makes expected calls", () => {
            const routerStub: Router = fixture.debugElement.injector.get(Router);
            const projectServiceStub: ProjectService = fixture.debugElement.injector.get(ProjectService);
            spyOn(routerStub, "navigate");
            spyOn(projectServiceStub, "GetActiveProject");
            comp.ngOnInit();
            expect(routerStub.navigate).toHaveBeenCalled();
            expect(projectServiceStub.GetActiveProject).toHaveBeenCalled();
        });
    });

});

为什么会抛出这个错误,我该如何解决这个错误?

编辑:我正在使用 Angular CLI 的默认 tsconfig 和 tsconfig.spec 文件。同时我已经升级到 Angular 6,我得到了 sam 错误。即使使用干净的配置文件创建新项目并替换 src 文件夹也无法解决错误。

4

1 回答 1

1

这些设置的组合冲突:

    declarations: [ AppComponent ],
    schemas: [ NO_ERRORS_SCHEMA ],

AppComponent 引用了另一个组件,而 testbed 模块无法找到该组件。无错误模式隐藏了 AppComponent 中的实际错误,但显示了 AppComponent 本身的错误,因为它无法正确加载。

要解决这个问题,您可以确保引用每个子组件,或者像这样导入整个模块:

    import: [ AppModule ],
于 2018-05-31T08:14:59.107 回答