(角度单元测试)如何在Jasmin中模拟输入属性?

时间:2019-09-17 10:38:40

标签: angular typescript unit-testing karma-jasmine angular-unit-test

我目前正在尝试模拟Angular单元测试的输入属性。不幸的是,我无法再进一步并反复收到以下错误消息:

  

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

我的HTML模板如下

<div class="container-fluid">
  <div class="row">
    <div class="col-12">
      <plot [data]="graph.data" [layout]="graph.layout"></plot>
    </div>
  </div>
</div>

我的组件是这样的:

...
export class ChartComponent implements OnInit {

  @Input() currentChart: Chart;

  currentLocationData: any;

  public graph = {
    data: [
      {
        type: 'bar',
        x: [1, 2, 3],
        y: [10, 20, 30],
      }
    ],
    layout: {
      title: 'A simple chart',
    },
    config: {
      scrollZoom: true
    }
  };

  ...
}

我的单元测试目前看来非常基础,但仍会引发上述错误:

describe('ChartComponent', () => {

  let component: ChartComponent;
  let fixture: ComponentFixture<ChartComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChartComponent],
      imports: [
        // My imports
      ]
    })
      .compileComponents();
  }));

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

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

我尝试了多种方法来模拟数据属性和currentChart @Input

实现此目标并修复单元测试的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

input属性就像任何变量一样工作。在您的beforeEach中,您可以将其设置为一个值

beforeEach(() => {
  fixture = TestBed.createComponent(ExplorerChartViewComponent);
  component = fixture.componentInstance;
  component.currentChart = someChart; // set input before first detectChanges
  fixture.detectChanges();
});

您可以阅读有关此here的更多信息。我更喜欢this approach

使用我的首选方法,您将拥有一个看起来像

的TestHost组件。
@Component({
  selector: 'app-testhost-chart',
  template: `<app-chart [currentChart]=chart></app-chart>`, // or whatever your Chart Component Selector is
})
export class TestHostComponent {
  chart = new Chart();
}

然后切换到创建新的测试主机。

 declarations: [ChartComponent, TestHostComponent ],
...
beforeEach(() => {
  fixture = TestBed.createComponent(TestHostComponent );
  component = fixture.debugElement.children[0].componentInstance;
  fixture.detectChanges();
});

但是我认为您可能还会遇到另外两个问题。特别是由于您要分配图

  1. 您要放置declarations: [ChartComponent],,但要创建fixture = TestBed.createComponent(ExplorerChartViewComponent);,我认为应该TestBed.createComponent(ChartComponent),除非存在复制/粘贴问题。
  2. 您的html中有<plot [data]="graph.data" [layout]="graph.layout"></plot>,它指示您未声明的绘图组件。您将需要声明要绘制的组件。我建议您做一些与TestHostComponent非常相似的事情,但要具有与真实PlotComponent相同的公共属性,这样就不会将PlotComponent的真实功能和依赖项引入到ChartComponent的单元测试中。