角度测试:“非法状态:无法为空组件加载指令摘要”

问题描述 投票:3回答:2

我的所有组件都没有通过单元测试,因此我在项目中创建了一个新组件来尝试和诊断。

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-thing',
  templateUrl: './thing.component.html',
  styleUrls: ['./thing.component.scss']
})
export class ThingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

thing.component.spec.ts文件如下

describe('ThingComponent', () => {
  let component: ThingComponent;
  let fixture: ComponentFixture<ThingComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ThingComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ThingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

Error: Illegal state: Could not load the summary for directive ThingComponent.测试失败我用xit关闭了所有其他测试,所以这是唯一运行的测试。

我试图将我的app.module.ts中的所有内容(提供者,导入等)移入文件中,这仍然提供相同的结果。

当我删除TestBed配置时,只需要一个

const comp = new ThingComponent();
expect(comp).toBeTruthy();

这传递了。但是,这不是实际组件的长期解决方案。

事物的版本:

"@angular/cli": "^1.7.2",
"@angular/compiler-cli": "^5.2.0",
"@angular/language-service": "^5.2.0",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-jasmine": "^1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
...
"@angular/animations": "^5.2.0",
"@angular/common": "^5.2.0",
"@angular/compiler": "^5.2.0",
"@angular/core": "^5.2.0",
"@angular/forms": "^5.2.0",
"@angular/http": "^5.2.0",
"@angular/platform-browser": "^5.2.0",
"@angular/platform-browser-dynamic": "^5.2.0",

任何帮助都将不胜感激,谢谢

更新我甚至将测试更改为expect(true).toBeTruthy(),它仍然得到相同的错误。我在ng g component提供的代码中没有更改任何其他内容。

另外,我在一个单独的目录中创建了一个新的角度项目,测试传递了这个新的空白项目。

angular angular-cli karma-jasmine
2个回答
1
投票

尝试将您的测试更改为:

it('should create', () => {
    fixture.detectChanges();

    fixture.whenStable().then(() => {
        expect(component).toBeTruthy();
    });
});

0
投票

固定它。我有一个管道有一个spec.ts文件如下:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [SafeHtmlPipe],
    providers: [DomSanitizer]
  })
  .compileComponents();
}));

describe('SafeHtmlPipe', () => {
  let pipe;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [DomSanitizer]
    });
  });

  beforeEach(inject([DomSanitizer], p => {
    pipe = p;
  }));

  xit('create an instance', () => {
    expect(pipe).toBeTruthy();
  });
});

请注意xit如何关闭测试。尽管如此,尽管被测组件没有使用这个管道,尽管我仍然在组件中导入/声明了它,但这导致了这个问题。

我不记得写这个,所以它可能是自动生成的,因为它正在测试的管道在构造函数中有一个DomSanitizer

删除文件就可以了。

© www.soinside.com 2019 - 2024. All rights reserved.