Last active
June 20, 2023 17:29
-
-
Save ernestlv/9153ee6a7529b5a0442b2118a6f4278c to your computer and use it in GitHub Desktop.
#Angular component test with change detection, click event and input validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DebugElement } from '@angular/core'; | |
import { TestBed } from '@angular/core/testing'; | |
import { By } from "@angular/platform-browser"; // predicates for browser environment | |
import { ReactiveFormsModule } from '@angular/forms'; | |
import { AppComponent } from './app.component'; | |
describe('AppComponent', () => { | |
beforeEach(() => TestBed.configureTestingModule({ | |
imports: [ReactiveFormsModule], | |
declarations: [AppComponent] | |
})); | |
it('should create the app', () => { | |
const fixture = TestBed.createComponent(AppComponent); | |
const app = fixture.componentInstance; | |
expect(app).toBeTruthy(); | |
}); | |
it(`should have as title 'ng-app'`, () => { | |
const fixture = TestBed.createComponent(AppComponent); | |
const app = fixture.componentInstance; | |
expect(app.title).toEqual('ng-app'); // component prop | |
}); | |
it('should render render header', () => { | |
const fixture = TestBed.createComponent(AppComponent); | |
fixture.detectChanges(); // triggers change detection updates component state | |
const domElement = fixture.nativeElement as HTMLElement; // shortcut for fixture.debugElement.nativeElement | |
expect(domElement.querySelector('h1')?.textContent).toContain('Forms'); | |
}); | |
it('should response to click button', () => { | |
const fixture = TestBed.createComponent(AppComponent); | |
fixture.detectChanges(); //angular change detection | |
const debugEle: DebugElement = fixture.debugElement; | |
const debugButton = debugEle.query( By.css("button.first-button") ); // platform agnostic element wrapper & query | |
debugButton.triggerEventHandler("click", null); | |
const debugInput = debugEle.query( By.css("input.first-input") ); // input element wrapper | |
expect(debugInput.nativeElement.value).not.toEqual(''); // access DOM element | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// jasmine cheatsheet -> https://devhints.io/jasmine
// angular debug API -> https://angular.io/guide/testing-components-basics#createcomponent
// quick examples -> https://blog.logrocket.com/angular-unit-testing-tutorial/