【问题标题】:Cannot read property 'name' of undefined in a spec无法读取规范中未定义的属性“名称”
【发布时间】:2020-02-04 10:26:17
【问题描述】:

我正在使用 jest 和 jasmine 作为测试配置进行 Angular8 项目。

.ts

// all imports are done correctly

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

  public info;
  public number;

  constructor(private InfoService: infoService ) {
  }

  ngOnInit() {
    this.getInfo();
  }

  public getInfo() {    
   this.info =  this.infoService.getData();   
   this.number = this.info.list[0].number;
  }

}

.spec

// all imports are done 

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ //imports done ],
      declarations: [ XYZComponent],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(XYZComponent);
    component = fixture.componentInstance;

    component.info = {
      'list':
      [
        {
       'fName':'Eddy',
       'lName':'He',
       'number: 123
     }
    ]
  }; 
   component.ngOnInIt(); 
  });

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

});

当在 .spec 文件中调用 ngOnInit() 时,它会抛出如下错误:

● XYZComponent › 应该创建

TypeError: Cannot read property 'list' of undefined

  43 |    this.info =  this.infoService.getData();
> 44 |    this.number = this.info.list[0].number;
     |                               ^
  46 |   }

【问题讨论】:

  • 可以把this.infoService.getData()的内容加进去吗?我认为问题可能就在那里。
  • 是的,我可以,但是我应该在 .spec 文件中的哪个位置添加您能指导我完成吗?
  • 哦,我的意思只是方法的内容,作为单独的代码sn-p。等nvm,发现错误,写个回复。

标签: angular testing jasmine


【解决方案1】:

即使你正在做:

component.info = {
  'list':
  [
    {
      'fName':'Eddy',
      'lName':'He',
      'number: 123
    }
  ]
};

在调用component.ngOnInit() 之前,这还不够,因为在您的ngOnInit() 方法中,您正在执行this.info = this.infoService.getData();,覆盖您的info 属性。

而且我相信在这个规范上下文中,这个方法返回undefined

更好的方法是模拟服务,提供一个虚假的getData 方法,该方法返回您希望组件处理的数据。

或者您可以将this.info = this.infoService.getData() 移动到构造函数,因为它不依赖于输入数据,这将使您的覆盖正常工作。

【讨论】:

  • 好的,所以我将尝试使用第一种方法来模拟服务并为其提供虚假调用...你能帮我举一些关于如何模拟服务等的示例吗?
  • angular.io/guide/testing#component-class-testing,搜索“MockUserService”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2022-01-22
  • 2021-11-13
  • 2022-01-14
  • 2022-06-22
相关资源
最近更新 更多