Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度测试用例上的未定义属性错误_Angular_Karma Jasmine - Fatal编程技术网

Angular 角度测试用例上的未定义属性错误

Angular 角度测试用例上的未定义属性错误,angular,karma-jasmine,Angular,Karma Jasmine,测试用例失败,并出现一个声明未定义属性的错误 我正在将roleID传递给getResults()。当我为('it should create component').truthy运行ng测试时,它抛出一个错误-->undefined roleID 我也在HTML中使用了类似*ngIf=“x?.roleID”的代码,在这里我得到了相同的错误 *.spec.ts文件示例: // it('should create', () => { // expect(component).toBeT

测试用例失败,并出现一个声明未定义属性的错误

我正在将roleID传递给getResults()。当我为('it should create component').truthy运行ng测试时,它抛出一个错误-->undefined roleID

我也在HTML中使用了类似*ngIf=“x?.roleID”的代码,在这里我得到了相同的错误

*.spec.ts
文件示例:

// it('should create', () => {
//     expect(component).toBeTruthy();
//   });
// While running the ng Test for this Component, it is throwing error like ngOnit() Id of undefined property

如果组件中未定义
this.inputArray
,则尝试访问
roleID
属性时,
ngOnInit
方法将失败。在测试期间,您必须确保正确初始化输入,即
inputArray
属性,这可以通过

a)将您的测试包装在一个测试驱动程序组件中,该组件可以充分设置输入,例如通过使用以下模板:

b)准备测试时初始化组件属性:

beforeEach(() => {
  fixture = TestBed.createComponent(YourComponent);
  component = fixture.componentInstance;
  // assign valid array to property here:
  component.inputArray = [{roleID: 1, ...}];
  // ... your ngOnInit will be run now:
  fixture.detectChanges();
});

您的问题在于:您没有测试台,也没有适当的导入来运行
ng测试

检查此项以基本掌握它可以解决您的问题

还有

您将拥有以下内容:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BannerComponent } from './banner.component';

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

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

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

  it('should create', () => {
    expect(component).toBeDefined();
  });
});
从'@angular/core/testing'导入{async,ComponentFixture,TestBed};
从“/banner.component”导入{BannerComponent};
描述('BannerComponent',()=>{
let组件:横幅组件;
let夹具:组件夹具;
beforeach(异步(()=>{
TestBed.configureTestingModule({
声明:[横幅组件]
})
.compileComponents();
}));
在每个之前(()=>{
fixture=TestBed.createComponent(BannerComponent);
组件=fixture.componentInstance;
fixture.detectChanges();
});
它('应该创建',()=>{
expect(component.toBeDefined();
});
});

很难看出问题所在,抱歉。您是否可以尝试使用创建一个最小的演示,以便我们重新制作此问题,谢谢您请查看此链接..谢谢您的帮助。如果您能提供一个示例来返回服务中函数的值,我们将不胜感激。例如,如果this.Id=this.xService.xfunction();我应该如何在测试床上为此声明一个mock?