Skip to content

Instantly share code, notes, and snippets.

@lancevo
Created August 17, 2017 19:45
Show Gist options
  • Save lancevo/83674ffa5ba386d5ef9a63a42ac7826e to your computer and use it in GitHub Desktop.
Save lancevo/83674ffa5ba386d5ef9a63a42ac7826e to your computer and use it in GitHub Desktop.
Mock Child Component
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: '<ul><li *ngFor="let i of numbers">{{i}}</li></ul>',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() numbers: number[];
constructor() {
}
ngOnInit() {
}
}
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ParentComponent } from './parent.component';
import { Input, Component, OnInit } from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-child', // make sure it has the same selector as the child component
template: `mock {{numbers.toString()}}`
})
class MockChildComponent implements OnInit {
@Input() numbers: number[];
constructor() {
console.log('initialize mockchild')
}
ngOnInit() {
}
}
describe('ParentComponent', () => {
let component: ParentComponent;
let fixture: ComponentFixture<ParentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ParentComponent,
MockChildComponent] // import the mock child component
});
TestBed.overrideComponent(ParentComponent, {
set: {
providers: [
{ provide: ChildComponent, useClass: MockChildComponent } // Overrride ChildComponent to use MockChildComponent
]
}
});
TestBed.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ParentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should render child component', () => {
const el = fixture.nativeElement;
expect(el.textContent.trim()).toBe('mock 1,2,3');
});
});
import { Component, OnInit } from '@angular/core';
import { ChildComponent } from '../child/child.component';
@Component({
selector: 'app-parent',
templateUrl: '<app-child [numbers] = "numbers"></app-child>',
styleUrls: ['./parent.component.css'],
providers: [ChildComponent]
})
export class ParentComponent implements OnInit {
public numbers = [1, 2, 3];
ngOnInit() {
}
}
@rtorres90
Copy link

Thanks you!

@pheetah
Copy link

pheetah commented Feb 24, 2022

Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment