this is from official documentation https://angular.io/docs/ts/latest/guide/testing.html#!#component-fixture. So you can create new input object expectedHero and pass it to the component comp.hero = expectedHero

Also make sure to call fixture.detectChanges(); last, otherwise property will not be bound to component.

Working Example

// async beforeEach
beforeEach( async(() => {
    TestBed.configureTestingModule({
        declarations: [ DashboardHeroComponent ],
    })
    .compileComponents(); // compile template and css
}));

// synchronous beforeEach
beforeEach(() => {
    fixture = TestBed.createComponent(DashboardHeroComponent);
    comp    = fixture.componentInstance;
    heroEl  = fixture.debugElement.query(By.css('.hero')); // find hero element

    // pretend that it was wired to something that supplied a hero
    expectedHero = new Hero(42, 'Test Name');
    comp.hero = expectedHero;
    fixture.detectChanges(); // trigger initial data binding
});
Answer from Vazgen Manukyan on Stack Overflow
Top answer
1 of 4
79

this is from official documentation https://angular.io/docs/ts/latest/guide/testing.html#!#component-fixture. So you can create new input object expectedHero and pass it to the component comp.hero = expectedHero

Also make sure to call fixture.detectChanges(); last, otherwise property will not be bound to component.

Working Example

// async beforeEach
beforeEach( async(() => {
    TestBed.configureTestingModule({
        declarations: [ DashboardHeroComponent ],
    })
    .compileComponents(); // compile template and css
}));

// synchronous beforeEach
beforeEach(() => {
    fixture = TestBed.createComponent(DashboardHeroComponent);
    comp    = fixture.componentInstance;
    heroEl  = fixture.debugElement.query(By.css('.hero')); // find hero element

    // pretend that it was wired to something that supplied a hero
    expectedHero = new Hero(42, 'Test Name');
    comp.hero = expectedHero;
    fixture.detectChanges(); // trigger initial data binding
});
2 of 4
57

If you use TestBed.configureTestingModule to compile your test component, here's another approach. It's basically the same as the accepted answer, but may be more similar to how angular-cli generates the specs. FWIW.

import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';

describe('ProductThumbnail', () => {
  let component: ProductThumbnail;
  let fixture: ComponentFixture<TestComponentWrapper>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ 
        TestComponentWrapper,
        ProductThumbnail
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();

    fixture = TestBed.createComponent(TestComponentWrapper);
    component = fixture.debugElement.children[0].componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

@Component({
  selector: 'test-component-wrapper',
  template: '<product-thumbnail [product]="product"></product-thumbnail>'
})
class TestComponentWrapper {
  product = new Product()
}
🌐
Medium
medium.com › better-programming › testing-angular-components-with-input-3bd6c07cfaf6
Testing Angular Components With @Input() | by Aiko Klostermann | Better Programming
December 8, 2023 - This article covers multiple ways of testing a component that binds an input via the @Input() decorator ... When developing an Angular component that takes an input, you might decide to unit test the whole component.
🌐
Testing-angular
testing-angular.com › testing-components
Testing Components – Testing Angular
... CounterComponent has an Input startCount that sets the initial count. We need to test that the counter handles the Input properly. For example, if we set startCount to 123, the rendered count needs to be 123 as well.
🌐
Plunker
embed.plnkr.co › mdsMBS76wyHKSmhZ0Yx3
angular 2 unit testing Component With @Input - Plunker
import { Component, Input} from '@angular/core'; import {UserModel} from './user-model' @Component({ selector: 'user-component', template: `<span>{{ user.fullname() }}</span>` }) export class UserComponent { @Input() user:UserModel; } export class UserModel { constructor( public firstname: string = '', public lastname: string = '' ) {}; fullname() { return (this.firstname + ' ' + this.lastname); } } import {UserComponent} from './user-component' import {UserModel} from './user-model' import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform
Top answer
1 of 1
21

Doing a test host component is a way to do it but I understand it can be too much work.

The ngOnInit of a component gets called on the first fixture.detectChanges() after TestBed.createComponent(...).

So to make sure it is populated in the ngOnInit, set it before the first fixture.detectChanges().

Example:

fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
component.inputproperty = value; // set the value here
fixture.detectChanges(); // first fixture.detectChanges call after createComponent will call ngOnInit

I assume all of that is in a beforeEach and if you want different values for inputproperty, you have to get creative with describes and beforeEach.

For instance:

describe('BannerComponent', () => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({declarations: [BannerComponent]}).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });

  describe('inputproperty is blahBlah', () => {
   beforeEach(() => {
     component.inputproperty = 'blahBlah';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is blahBlah', () => {
     // test when inputproperty is blahBlah
   });
  });

  describe('inputproperty is abc', () => {
   beforeEach(() => {
     component.inputproperty = 'abc';
     fixture.detectChanges();
   });

   it('should do xyz if inputProperty is abc', () => {
     // test when inputproperty is abc
   });
  });
});
🌐
Angulardart
angulardart.xyz › guide › testing › component › input-and-output
Component Testing: @Input() and @Output()
Testing basics is covered in Writing component tests: Basics. For in-depth coverage of the package capabilities, see the package:test documentation. ... A complementary package that provides a means of interacting with Angular components created as test fixtures.
🌐
DEV Community
dev.to › fransaoco › testing-angular-components-with-inputs-and-outputs-using-jest-1ch6
Testing Angular Components with Inputs and Outputs using Jest - DEV Community
April 21, 2025 - Control input values passed to the component. Capture emitted events exactly like a real parent would. ... import { ComponentFixture, TestBed } from '@angular/core/testing'; import { IoComponent } from './io.component'; import { Component, ViewChild ...
🌐
CodeCraft
codecraft.tv › courses › angular › unit-testing › components
Testing Components • Angular - CodeCraft
We’ll continue with our example of testing a LoginComponent. We are going to change our component into a more complex version with inputs, outputs, a domain model and a form, like so: import {Component, EventEmitter, Input, Output} from '@angular/core'; export class User { (1) constructor(public email: string, public password: string) { } } @Component({ selector: 'app-login', template: ` <form> <label>Email</label> <input type="email" #email> <label>Password</label> <input type="password" #password> <button type="button" (2) (click)="login(email.value, password.value)" [disabled]="!enabled">
Find elsewhere
🌐
Decoded Script
decodedscript.com › angular-component-testing-with-input-and-output
Angular component testing with @input and @output - Decoded Script
October 8, 2022 - data between components in angular 11 – @input, @Output, @ViewChild and Service · The source code is available on Stackblitz of theAngular component testing with @input, @output, and service.
🌐
Medium
otchibozo.medium.com › angular-unit-testing-with-input-and-output-in-an-angular-component-df11296f9c9a
Angular Unit Testing with @Input() and @Output() in an Angular Component | by Olympe Tchibozo | Medium
February 16, 2024 - Upon executing this code, an instance of the CarProfileComponent to be tested is created, a call to the `emitStartEvent method is simulated, and the emission of the `startEvent` with the value ‘Toyota‘ is verified. Ultimately, as demonstrated through this example, writing unit tests is not as daunting a task as it might seem. We hope that our unit tests on an Angular application component, utilising properties and events with the example of car profiles, have helped to demystify them.
🌐
Angular
v17.angular.io › guide › testing-components-scenarios
Component testing scenarios
Angular is a platform for building mobile and desktop web applications. Join the community of millions of developers who build compelling user interfaces with Angular.
🌐
Nativescript
discourse.nativescript.org › angular
Unit Testing a Custom Component with @Input - Angular - NativeScript Community Forum
January 18, 2017 - Have you had any luck with this? I linked the code below that is giving me trouble. It should be a very simple test, but it’s turning out to be a headache. ... import { Component } from "@angular/core"; @Component({ selector: "links", templateUrl: "./components/links/links.component.html" }) export class LinksComponent { test = "test"; public constructor() { } }
Top answer
1 of 2
4

the following works:

Include this import:

import { of } from 'rxjs';

Change the beforeEach block for the file to:

beforeEach(() => {
  fixture = TestBed.createComponent(BugsTableComponent);
  component = fixture.componentInstance;

  // needed because ngAfterViewInit gets called and if there isn't an observable to subscribe to it will fail
  component.bugsDataService = of(null);

  fixture.detectChanges();
});

Write a test:

it('Should assign the input value to bugsdata', () => {
  // Arrange
  component.bugsData = {}; // to make sure it's empty at the start
  const resultFromService = {hello: 'world'};
  component.bugsDataService = of(resultFromService); // this creates an observable from resultFromService

  // Act
  component.ngAfterViewInit();

  // Assert
  expect(component.bugsData).toEqual(resultFromService);
});

Some notes:

  • I've noticed is that your component has a ngAfterViewInit but the class does not implement it. If you're not using ngOnInit then replace it in the class declaration with ngAfterViewInit and update the imports.
  • If you don't want to do the change I suggested in the beforeEach block you can move the subscribe line from ngAfterViewInit to a separate method that is called by ngAfterViewInit. However, you'll then need to spy on it so it doesn't actually get called.
2 of 2
0
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BugsTableComponent ],
      imports: [],
      providers: [BugsDataService] // inject service here 
    })
    .compileComponents();
  }));

This should fix the bug but

If you want to Simulate the actual behaviour of the service better way would be to create a mock service which extends BugsDataService and use it in the unit test cases to provide Mock Data

example

@Injectable()
export class BugsDataMockService extends BugsDataService {

overridenMethod() {
return Observable.of( { data : yourmockresponse });
}


And in your Spec file (Unit test)
beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BugsTableComponent ],
      imports: [],
      providers: [ { provide: BugsDataService, useClass: BugsMockDataService } ] // Use Mock Service instead of original one 
    })
    .compileComponents();
  }));
🌐
GitHub
github.com › angular › angular › issues › 54039
Components with a 'required' signalized input cannot be directly unit tested · Issue #54039 · angular/angular
January 23, 2024 - However you can write this sort of test with a non-signalized required input ie @Input({required: true}) myInput!: string; (which is why I'm calling this a regression). The workaround as via https://stackoverflow.com/questions/77838277/how-...
Author   bdirito
🌐
GitHub
github.com › angular › angular › issues › 22216
How test component @Input() set foo(bar) method. · Issue #22216 · angular/angular
February 14, 2018 - On Stackoverflow I did not find support, so I have to write here. https://stackoverflow.com/questions/48681990/test-method-setter-input-angular-4-karma ... `import {Component, Input} from '@angular/core'; import {CameraModel, VideoModel} from "../../models"; import {Translation, TranslationService} from "angular-l10n"; import {Utilities, ISODateTime} from "../../utilities/utilities"; import {Observable} from "rxjs"; import {DashboardService} from "../../services/dashboard/dashboard.service"; import {OverlayService} from "../../services/overlay/overlay.service"; import {DashboardVideoAddComponent} from "../dashboard-video-add/dashboard-video-add.component";
Author   ALPNP
🌐
Medium
shashankvivek-7.medium.com › testing-angular-component-with-templateref-as-input-b96313b37cd4
Testing Angular Component with TemplateRef as “@Input()” | by Shashank Vivek | Medium
October 29, 2019 - To test this component, we have ... TemplateRef as @Input() , so we will start writing its spec file with a temporary WrapperComponent which is created just for the purpose of testing....