如何使用 ng-mocks 测试扩展基础组件的组件

How to test component which extends base component with ng-mocks

我有 CakeItemContainerComponent,它扩展了 ItemContainerComponent,我尝试用 ng-mocks 测试它。这是我正在尝试做的事情:

@Component({
  selector: 'app-item-container',
  template: ''
})
export class ItemContainerComponent implements OnInit {
  items$: Observable<Item[]>;
  constructor(protected itemService: ItemService) {}

  ngOnInit(): void {
    this.items$ = this.itemService.getItems();
  }
}

@Component({
  selector: 'app-cake-item-container',
  template: '<div class="cake-container"><span>{{ title }}</span><div *ngFor="let item of items$ | async">{{item.name}}</div></div>'
})
export class CakeItemContainerComponent extends ItemContainerComponent implements OnInit {
  title: string;
  constructor(itemService: ItemService) {
    super(itemSerivce);
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.title = 'Some title';
  }
}

一切正常,但是当我尝试使用 ng-mocks 对其进行测试时,我得到了 'NG0304: 'app-cake-item-container' is not a known element:

describe('CakeItemContainerComponent', () => {
  beforeEach(() => {
    return MockBuilder(CakeItemContainerComponent)
             .mock(ItemService)
             .build();
  });

  it('should be created', () => {
    const fixture = MockRender(CakeItemContainerComponent);
    const component = fixture.point.componentInstance;
    fixture.detectChanges();
    expect(component).toBeDefined();
  });
});

我没想到如此基础和经典的测试会产生任何问题。

如果我收到无法识别的子组件,我不会感到惊讶,这很好。但我从未收到消息,测试组件无法识别...我是 ng-mocks 的新手所以可能我做错了什么,但是什么??

感谢任何想法:)

有2个错误:

  • beforeEach 应该 return 来自 MockBuilder
  • 的承诺
  • it 应该使用 MockRender

一个工作示例:https://codesandbox.io/s/romantic-aryabhata-shgs7s?file=/src/test.spec.ts

describe('CakeItemContainerComponent', () => {
  beforeEach(() => {
    return MockBuilder(CakeItemContainerComponent)
             .mock(ItemService);
             // .build(); // <- remove
  });

  it('should be created', () => {
    const fixture = MockRender(CakeItemContainerComponent); // <- change
    const component = fixture.point.componentInstance;
    fixture.detectChanges();
    expect(component).toBeDefined();
  });
});