模板变量在运行茉莉测试用例时引发未定义的错误

时间:2019-05-06 06:07:38

标签: angular jasmine karma-jasmine

在运行单元测试用例时出现以下错误,

TypeError: Cannot read property 'type' of undefined

以下是我的规格

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

  const mock = {
    "type": "list",
      "items": [
        {
          "type": "unordered-list-item",
          "text": "Unordered Item One",
          "depth": 1,
        }
      ]
  }
  cacheTestbed({
    imports: [ContentComponentsModule],

  });

  beforeEach(() => {
    fixture = TestBed.createComponent(ListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.contentOnCreate(mock)
  });

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

这是我的HTML,

<ng-container *ngIf="listItems.type==='unordered-list-item'">
  <ul *ngIf="listItems.children.length > 0" class="bw-information-ul-with-disc">
    <bw-information-recursive-list *ngFor="let child of listItems.children" [child]="child"></bw-information-recursive-list>
  </ul>
</ng-container>

listItems.type未定义。如果我注释了html代码,则所有测试用例都将通过。

我什至试图在listItems内为beforeEach分配模拟值,但遇到相同的错误却无法正常工作。

请帮助。

***********更新*******

我的组件规格

Component.Ts

export class ListComponent {
  public listItems: RecursiveList;

  contentOnCreate(values: ListItems): void {
    this.listItems = this.createListTree(values.items);
  }

  createListTree(listItem: ListItem[]): Item {
    const root: Item = { text: 'root', children: [], type: listItem[0].type }
    const stack: Item[] = []
    const firstChildOfRoot = {
      text: listItem[0].text,
      children: [],
      type: listItem[0].type
    }
    root.children.push(firstChildOfRoot)
    stack.push(root)
    stack.push(firstChildOfRoot)

    for (let i = 1; i < listItem.length; i++) {
      const flatItem = listItem[i]
      const depthDiff = flatItem.depth - (stack.length - 1)
      if (depthDiff <= 0) {
        this.removeFromEnd(stack, -depthDiff + 1)
      }
      const stackTop = stack[stack.length - 1]
      const newEl = {
        text: flatItem.text,
        children: [],
        type: flatItem.type
      }
      stackTop.children.push(newEl)
      stack.push(newEl)
    }
    return root
  }

  removeFromEnd<T>(array: T[], count: number) {
    array.splice(array.length - count, count)
  }
}

1 个答案:

答案 0 :(得分:0)

尝试在fixture.detectChanges();之后移动component.contentOnCreate

  beforeEach(() => {
    fixture = TestBed.createComponent(ListComponent);
    component = fixture.componentInstance;
    component.contentOnCreate(mock)
    fixture.detectChanges();
  });