我有一个非常简单的组件:
import { Component } from '@angular/core';
@Component({
selector: 'loading',
templateUrl: './loading.component.html',
styleUrls: ['./loading.component.scss']
})
export class LoadingComponent {
}
仅显示静态加载徽标。完全没有交互性。我写了一个测试来测试其实例化:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoadingComponent } from './loading.component';
describe('LoadingComponent', () => {
let component: LoadingComponent;
let fixture: ComponentFixture<LoadingComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoadingComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoadingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should exist', () => {
expect(component).toBeTruthy();
});
});
在Firefox中,此测试引发错误:j is undefined
,在Chromium浏览器中,我看到Cannot read property 'startTime' of undefined
。模板很简单:
Sample Text
为了弄清楚发生了什么。因此,在这三个文件的任何地方都没有提及“ startTime”-发生了什么??
我在其他组件中确实使用了startTime
属性,但我不知道这将如何/为什么重要。
通过添加以下内容,我就可以使此错误消失:
afterAll(() => {
TestBed.resetTestingModule();
});
项目中的每个测试。我不愿公开这个问题,因为我不知道:
答案 0 :(得分:0)
您看到的错误绝对不是来自您发布的组件和规格文件。您看到的错误很可能是由执行异步操作的组件引起的,并且在实例化它的规范完成后发生了该错误。
首先,在此spec文件的描述前加一个f。
fdescribe('LoadingComponent', () => {
这将导致规范运行器仅运行该文件。您会看到它运行正常。
接下来,您要删除f并在项目中搜索startTime,请尝试运行一次使用startTime属性的组件的规格。
如果找不到它,则一次在它们的描述前面加上一个x,最终您会发现是哪个错误引起了错误,因为在规范上有x时不会发生错误。
任何具有异步功能的规范都应使用异步功能,以便在继续下一个规范之前,它等待所有异步活动完成。