Javascript 角度10测试:组件解析程序数据订阅错误
在过去的几天里,我一直在努力跟上Javascript 角度10测试:组件解析程序数据订阅错误,javascript,angular,typescript,karma-jasmine,Javascript,Angular,Typescript,Karma Jasmine,在过去的几天里,我一直在努力跟上ng test的速度,所有的spec文件@angular/cli都是在创建组件时创建的 当我在自己的投资组合网站上工作时,我遇到了一个我似乎无法理解或解决的问题 我有这个组件(相当香草的东西): 这将错误更改为(这让我更加困惑): TypeError:中未定义this.route.datahttp://localhost:9876/_karma_webpack_/main.js (第1575行) 社区面临的问题:我如何解决这个问题?出现此错误的原因是什么?不是提供
ng test
的速度,所有的spec文件@angular/cli
都是在创建组件时创建的
当我在自己的投资组合网站上工作时,我遇到了一个我似乎无法理解或解决的问题
我有这个组件(相当香草的东西):
这将错误更改为(这让我更加困惑):
TypeError:中未定义this.route.datahttp://localhost:9876/_karma_webpack_/main.js (第1575行)
社区面临的问题:我如何解决这个问题?出现此错误的原因是什么?不是提供原始的
项目详细信息,而是在其数据属性中提供一个可观察的:
import {of} from 'rxjs';
...
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
// Properly provide the activated route mock object.
{ provide: ActivatedRoute, useValue: { data: of(projectDetails) } }
],
declarations: [ ProjectsDetailsComponent ]
})
.compileComponents();
}));
...
如果查看如何访问路由数据,可以看到它使用了一个可观察的:
this.route.data.subscribe(content => {...});
感谢您的快速回复!不幸的是,这并没有奏效。错误仍然存在。奇怪。在您的测试中,错误为this.route.data未定义
,这意味着您没有为this.route.data
提供值。这是有意义的,因为您直接为ActivatedRoute提供projectDetails对象。如果您按照我指定的方式将提供者添加到测试中,它应该可以工作。也许你在执行测试时有缓存问题?哦,天哪。这太尴尬了。你知道我在文件constprojectdetails:projectDetails={/*validcontent*/}
中是怎么说的吗?结果是。。。这是无效的。修复该对象使一切都与您提供的答案一致。掌纹
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'
import { ProjectsDetailsComponent } from './projects-details.component';
import { ProjectDetails } from './project-details'
import { ActivatedRoute } from '@angular/router';
describe('ProjectsDetailsComponent', () => {
let component: ProjectsDetailsComponent;
let fixture: ComponentFixture<ProjectsDetailsComponent>;
const projectDetails : ProjectDetails = {/* valid content */}
beforeEach(async(() => {
TestBed.configureTestingModule({
// imports:[
// RouterTestingModule
// ],
providers: [
{ provide: ActivatedRoute, useValue: projectDetails }
],
declarations: [ ProjectsDetailsComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProjectsDetailsComponent);
component = fixture.componentInstance;
component.currentContent = projectDetails
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import {of} from 'rxjs';
...
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
// Properly provide the activated route mock object.
{ provide: ActivatedRoute, useValue: { data: of(projectDetails) } }
],
declarations: [ ProjectsDetailsComponent ]
})
.compileComponents();
}));
...
this.route.data.subscribe(content => {...});