如何用ng-mock测试扩展基组件的组件



我有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-mock测试它时,我得到'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-mock所以可能我做错了什么,但什么??

谢谢你的建议

有两个错误:

  • beforeEach应该返回MockBuilder的Promise
  • 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();
});
});

最新更新