Check out our Angular Book Series.

How do I test the text of an HTML Element with Jasmine, Karma, and Angular?

I think this should have been simple, but my Google Fu was failing me. I'm working on an Angular app, as I often do, and was writing unit tests to verify that property changes inside a Component's class were reflected inside the view template.

The Component and View

I'm just going to use truncated code here, but the component had a property like this:


export class MyClass{
@Input() buttonText : string = "";
}

The template had something like this:


<button class="myButton">{{buttonText}}</button>

Change the value on the component, and the view should change. This sort of binding is basic to Angular. How do we test that?

Write the Tests

First, you set up the TestBed:


beforeEach(async(() =>
{
TestBed.configureTestingModule({
declarations: [ MyComp ]
})
.compileComponents();
fixture = TestBed.createComponent(MyComp);
component = fixture.componentInstance;
}));

This should be pretty standard, and this code is almost copied verbatim from the Angular CLI defaults.

Now your test should do something like this. First set the value on the component


const defaultButtonText = "Something"
component.buttonText = defaultButtonText ;

Now you have to detect the changes to force the view to refresh itself:


fixture.detectChanges();

Get the HTML Element:


const button = fixture.debugElement.query(By.css('.myButton'));

And check the button's TextContent:


expect(button.nativeElement.textContent.trim()).toBe(defaultButtonText )

You're code should be all set to test.

For completeness, here is the full test:


it('Set Button Text to Something', () =>
{
const defaultButtonText = "Something"
component.buttonText = defaultButtonText ;
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('.myButton'));
expect(button.nativeElement.textContent.trim()).toBe(defaultButtonText )
});

I hope this helps someone.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.