change the value of the currentUser variable:

it('should open the menu when the button menu is clicked', () => {
  const fixture = TestBed.createComponent(HeaderComponent);
  const component = fixture.componentInstance;
  component.currentUser = true;

  fixture.detectChanges();

  const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
  expect(menuDebugElement).toBeTruthy();
});

I created an entire test and it works for me

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { TestTComponent } from './test-t.component';
import { By } from '@angular/platform-browser';

fdescribe('TestTComponent', () => {
  let component: TestTComponent;
  let fixture: ComponentFixture<TestTComponent>;

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

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

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

    fixture.detectChanges();

    const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
    expect(menuDebugElement).toBeTruthy();
  });
});
Answer from Chris on Stack Overflow
Top answer
1 of 2
6

change the value of the currentUser variable:

it('should open the menu when the button menu is clicked', () => {
  const fixture = TestBed.createComponent(HeaderComponent);
  const component = fixture.componentInstance;
  component.currentUser = true;

  fixture.detectChanges();

  const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
  expect(menuDebugElement).toBeTruthy();
});

I created an entire test and it works for me

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { TestTComponent } from './test-t.component';
import { By } from '@angular/platform-browser';

fdescribe('TestTComponent', () => {
  let component: TestTComponent;
  let fixture: ComponentFixture<TestTComponent>;

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

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

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

    fixture.detectChanges();

    const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
    expect(menuDebugElement).toBeTruthy();
  });
});
2 of 2
0

The problem is fixture.detectChanges(); triggers change detaction cycle and when you read value from html component not finished to update itself.

You solve using "whenStable()" function

  it('should open the menu when the button menu is clicked', () => {
    const fixture = TestBed.createComponent(HeaderComponent);
    component.currentUser = true;

    fixture.detectChanges();

    fixture.whenStable()
        .then(() => {
            const menuDebugElement = fixture.debugElement.query(By.css('.menu-button'));
            expect(menuDebugElement).toBeTruthy();
        });
    
  });
🌐
Testing-angular
testing-angular.com › testing-components
Testing Components – Testing Angular
To prepare the rendering, an instance of the Component is created, dependencies are resolved and injected, inputs are set. Finally, the template is rendered into the DOM. For testing, you could do all that manually, but you would need to dive deeply into Angular internals. ... Instead, the Angular team provides the TestBed to ease unit testing.
Discussions

angular - Angular2 unit test with @Input() - Stack Overflow
0 Angular unit test for component with service arguments More on stackoverflow.com
🌐 stackoverflow.com
Angular Unit Test: Access template variable - Stack Overflow
Nothing wrong with adding variables to your component to facilitate unit testing, just add a comment for other developers and you're all set. More on stackoverflow.com
🌐 stackoverflow.com
Angular unit test input value - Stack Overflow
I have been reading official Angular2 documentation for unit testing (https://angular.io/docs/ts/latest/guide/testing.html) but I am struggling with setting a component's input field value so that ... More on stackoverflow.com
🌐 stackoverflow.com
How do I update component variables in Angular unit tests?
I am having a problem where I set the "headerButtons" and "contractLoaded" component variables in my test but it does not seem to change the values. If I console out or use a de... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Angular
v17.angular.io › guide › testing-components-basics
Angular
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.
🌐
CodeCraft
codecraft.tv › courses › angular › unit-testing › components
Testing Components • Angular - CodeCraft
We just have a few more debug elements stored on our test suite which we’ll inspect or interact with in our test specs. ... We need to be able to change the input property enabled on our component. We need to check that the button is enabled or disabled depending on the value of our input property. Solving the first is actually very easy. Just because it’s an @Input doesn’t change the fact it’s still just a simple property which we can change like any other property, like so: it('Setting enabled to false disables the submit button', () => { component.enabled = false; });
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()
}
🌐
Testim
testim.io › blog › angular-component-testing-detailed-guide
Angular Component Testing: A Detailed How-To With Examples
June 18, 2025 - In order to test our Angular component’s functionality, we need to import some Angular testing tools, which we’ll use alongside Jasmine. TestBed is used to configure and initialize the environment unit tests. The describe code block represents the test suite for AppComponent. It contains specs and additional code that’s used for testing AppComponent. beforeEach is a global function in Jasmine that runs some setup ...
🌐
Semaphore
semaphore.io › home › testing components in angular 2 with jasmine
Testing Components in Angular 2 with Jasmine - Semaphore Tutorial
April 21, 2021 - TestBed is the main entry to all of Angular’s testing interface. It will let us create our components, so they can be used to run unit tests. We also pull in the FormGroup and ReactiveFormsModule classes. FormGroup will just be used to test the type of a variable.
🌐
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.
Find elsewhere
🌐
Angular
angular.dev › guide › testing › components-scenarios
Component testing scenarios • Angular
The testing goal is to verify that such bindings work as expected. The tests should set input values and listen for output events. The DashboardHero component is a tiny example of a component in this role. It displays an individual hero provided by the Dashboard component.
🌐
Angular
angular.dev › guide › testing › components-basics
Basics of testing components • Angular
You will add more tests as this component evolves. Rather than duplicate the TestBed configuration for each test, you refactor to pull the setup into a beforeEach() and some supporting variables:
Top answer
1 of 1
1

That is strange. Can you show the HTML and component typescript as well?

I think I have an idea though about the issue you could be facing.

it('should display the correct amount of header buttons', () => {
    // get rid of this variable
    // const debugEl: DebugElement = fixture.debugElement;

    component.headerButtons = 'basic';
    fixture.detectChanges();

    // Change this line to be fixture.debugElement and not debugEl
    expect(fixture.debugElement.queryAll(By.css('.header-banner__btn-link')).length).toEqual(
      2
    );

    component.headerButtons = 'full';
    component.contractLoaded = true;
    fixture.detectChanges();
    // Change this line to be fixture.debugElement and not debugEl
    expect(
      fixture.debugElement.queryAll(By.css('.header-banner__btn-link')).length
    ).toBeGreaterThan(2);
  });

The issue is the debugEl. It becomes stale after you change component variables so you always need a new debugEl after changing variables. I think this is most likely the issue.

====== Edit ====== Maybe we should mock ContractEventService instead of providing the real one.

Try this:

let component: HeaderBannerComponent;
let fixture: ComponentFixture<HeaderBannerComponent>;
let mockContractEventService: jasmine.SpyObj<ContractEventService>;

  beforeEach(() => {
    // the first string argument is just an identifier and is optional
    // the second array of strings are public methods that we need to mock
    mockContractEventService = jasmine.createSpyObj<ContractEventService>('ContractEventService', ['getContractLoaded']);
    TestBed.configureTestingModule({ 
      declarations: [HeaderBannerComponent], 
      // provide the mock when the component asks for the real one
      providers: [{ provide: ContractEventService, useValue: mockContractService }] 
    });
    fixture = TestBed.createComponent(HeaderBannerComponent);
    component = fixture.componentInstance;
    // formatting is off but return a fake value for getContractLoaded
 mockContractEventService.getContractLoaded.and.returnValue(of(true));
    // the first fixture.detectChanges() is when ngOnInit is called
    fixture.detectChanges();
  });

it('should display the correct amount of header buttons', () => {
    // get rid of this variable
    // const debugEl: DebugElement = fixture.debugElement;

    component.headerButtons = 'basic';
    // The issue was that we are not calling setButtons
    // manually call setButtons
    component.setButtons();
    fixture.detectChanges();

    // Change this line to be fixture.debugElement and not debugEl
    expect(fixture.debugElement.queryAll(By.css('.header-banner__btn-link')).length).toEqual(
      2
    );

    component.headerButtons = 'full';
    component.contractLoaded = true;
    // manually call setButtons
    component.setButtons();
    fixture.detectChanges();
    // Change this line to be fixture.debugElement and not debugEl
    expect(
      fixture.debugElement.queryAll(By.css('.header-banner__btn-link')).length
    ).toBeGreaterThan(2);
  });
🌐
Better Programming
betterprogramming.pub › testing-angular-components-with-input-3bd6c07cfaf6
Testing Angular Components With @Input() | by Aiko Klostermann | Better Programming
December 8, 2023 - To verify that processInput() correctly upcases our input, we can simply assign a test value to the input variable and assert that, after calling the method, the displayed input is in ALL CAPS.
🌐
DEV Community
dev.to › coly010 › unit-testing-angular-component-testing-2g47
Unit Testing Angular - Component Testing - DEV Community
February 15, 2020 - The third and final sction is Assert: Here you will make verify that the unit performed as expected. In our test above we set what we are expecting the value to be if the function performs correctly and we are setting the data we will use to test the function. We then call the sum() function on our previously arranged test data and store the result in a total variable.
🌐
DanyWalls
danywalls.com › how-to-test-components-in-angular-using-testbed
How To Test Components In Angular Using Testbed | DanyWalls
January 16, 2023 - We create the player-list.component.spec.ts , adding the describe with the test title. ... Declare the fixture variable to store the component using ComponentFixture , and set the variable using the type PlayerListComponent.
🌐
Halodoc Blog
blogs.halodoc.io › angular-unit-testing
Angular Unit Testing - Why and How to unit test angular applications
July 5, 2023 - To Test this lets first set up the test Environment ... Like we did for class, we create a test scoped variable, then ComponentFixture gives us the reference to the component instance to be tested. Going forward this fixture can also be used for template testing. Components often depend on services that angular injects into constructor so, for those of the injected service.
🌐
LogRocket
blog.logrocket.com › home › angular unit testing tutorial with examples
Angular unit testing tutorial with examples - LogRocket Blog
November 19, 2024 - When you use the Angular CLI to scaffold a project, it generates unit test specs for the default app component. Following the initial project setup, we’ll need to write test specifications for each component, directive, and more.
🌐
Open Water Foundation
learn.openwaterfoundation.org › owf-learn-angular › unit-testing
Unit Testing - Learn / Angular
Unit tests should be fast, reliable, and repeatable so that they can be run efficiently to confirm software functionality. Before beginning the following demonstration, the initial test file that is created whenever a new Angular project is created will be reviewed. When a new Angular project is created, a default component ...