Overriding Dependencies for Testing

    • overrideModule
    • overrideComponent
    • overrideDirective
    • overridePipe
      For example, you might want to override the template of a component. This is useful for testing a small part of a large component, as you can ignore the output from the rest of the DOM and only focus on the part you are interested in testing.
    1. import {MessageComponent} from './message.component';
    2. import { provide } from '@angular/core';
    3. import {
    4. async,
    5. inject,
    6. TestBed,
    7. } from '@angular/core/testing';
    8. describe('MessageComponent', () => {
    9. let fixture;
    10. beforeEach(() => {
    11. TestBed.configureTestingModule({
    12. declarations: [MessageComponent],
    13. providers: []
    14. });
    15. fixture = TestBed.overrideComponent(MessageComponent, {
    16. set: {
    17. template: '<span>{{message}}</span>'
    18. }})
    19. .createComponent(MessageComponent);
    20. fixture.detectChanges();
    21. });
    22. it('should set the message', async(inject([], () => {
    23. fixture.componentInstance.setMessage('Test message');
    24. fixture.detectChanges();
    25. fixture.whenStable().then(() => {
    26. const compiled = fixture.debugElement.nativeElement;
    27. expect(compiled.querySelector('span').innerText).toEqual('Test message');
    28. });
    29. })));
    30. });