Home > Mobile >  How to test component which extends base component with ng-mocks
How to test component which extends base component with ng-mocks

Time:04-26

I have CakeItemContainerComponent which extends ItemContainerComponent and I try to test it with ng-mocks. Here what I'm trying to do:

@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 ><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';
  }
}

Everything works fine, but when I'm trying to test it with ng-mocks I'm getting '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();
  });
});

I wouldn't thought that so basic and classic test will generate any issues.

I wouldn't be surprised if I would receive unrecognized child component, that's fine. But I never received message, that testing component is unrecognized... I'm new to ng-mocks so probably I'm doing something wrong, but what??

thanks for any thoughts :)

CodePudding user response:

There are 2 mistakes:

  • beforeEach should return the Promise from MockBuilder
  • it should use MockRender

A working example: 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();
  });
});
  • Related