繁体   English   中英

业力输入参数单元测试

[英]Karma Input parameter unit testing

我在angular 6中遇到单元测试的问题。我正在尝试使用一个input()参数测试一个简单的组件。 问题是我不知道如何继续。 执行ng test时收到错误消息:

TypeError:无法读取未定义的属性“ id_profile”

我的代码是这样的:

模型

export class Profile {    
  id_profile: string;
  name: string;
}

HTML

<div class="card" (click)="clicked()">
    <div id="profile">{{profile.id_profile}}</div>
    <i class="material-icons">vpn_key</i>
</div>

零件

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';    
import { Profile } from 'app/models';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})

export class ProfileComponent {

  @Input() profile: Profile;

  private profileShown: Profile;

  constructor(public router: Router) {
  }

  OnInit() {
    this.profileShown= this.profile;
  }

  clicked() {
    this.profileShown= this.profile;
    this.router.navigate(['pages']);
  }   
}

最后,我的测试:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ProfileComponent} from './profile.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ProfileComponent]
    })
      .compileComponents();
  }));

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

  it('should create', () => {
    component.profile= {
      'id_profile': '12345678A',
      'name': 'SUMUM_D',      
    };
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });
});

我该怎么做才能解决这个问题? 我在做正确的事吗? 提前致谢

在将数据设置为@Input()属性之前,请不要运行detectChanges ,因为它会渲染视图并为未初始化的属性引发错误。

beforeEach(() => {
    fixture = TestBed.createComponent(ProfileComponent);
    component = fixture.componentInstance;
    // fixture.detectChanges();    -- Remove this line
});

请让我知道它是否仍然显示错误

 it('should create', () => {
    component.profileShown= {
      'id_profile': '12345678A',
      'name': 'SUMUM_D',      
    };
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM