I am new to angular 2 karma testing. I was trying to test a simple component which has a title , an input box and a button.
I learned the basics of karma test from angular.io and was trying to test that the value contains in the input box is right or not. but was getting error "null is not an object" when i tried to get the input element in the test.
To solve that error, i gave it inside fixture.whenStable() but now having the error "undefined is not a constructor" . i don't know why that happens. Below is my component, spec.ts, html file.
Thanks.
In banner.component.html
<h1 id="titleId" class="titleClass"></h1>
<input id="inputId" type="text" *ngIf="name!==undefined" [(ngModel)]="name"/>
<button id="btnId" type="button" >Click Me!</button>
In banner.component.ts
@Component({
selector: "app-banner",
templateUrl: "./banner.component.html",
providers: [AbcService],
})
export class BannerComponent {
private abData: abData;
private name: string;
title = "Test Karma";
user = {
userName: "Nokia",
size: 45,
}
constructor( @Inject(AbcService) private abcService: AbcService) {
}
ngAfterViewInit(): void {
this.setAlternative();
}
setAlternative() {
this.abcService.getAlternativeDetails(10752)
.subscribe(abData=> {
this.abData= abData;
this.name = this.abData.name;
});
}
}
In banner.component.spec.ts
class AlternativeDetailsServiceSpy {
getAlternativeDetails = jasmine.createSpy("getAlternativeDetails").and.callFake(() =>
Promise.resolve(true).then(() => Object.assign({}, {})));
}
describe("BannerComponent", () => {
let comp: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
let de;
let el;
let input;
let inputEl;
let spy: AlternativeDetailsServiceSpy;
// async beforeEach
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [BannerComponent], // declare the test component
providers: [{ provide: AbcService, useValue: {} }]
}).overrideComponent(BannerComponent, {
set: {
providers: [
{ provide: AbcService, useClass: AbcServiceSpy }
]
}
}).compileComponents(); // compile template and css
}));
// synchronous beforeEach
beforeEach(() => {
let hdsSpy: AbcServiceSpy ;
fixture = TestBed.createComponent(BannerComponent);
comp = fixture.componentInstance; // BannerComponent test instance
hdsSpy = fixture.debugElement.injector.get(AbcService);
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css("#btnId"));
el = de.nativeElement;
// input = fixture.debugElement.query(By.css("#inputId"));
// inputEl = input.nativeElement;
});
it("should check the object of bannercomponent is created", () => {
expect(comp instanceof BannerComponent).toBe(true);
});
it("should be having empty value", () => {
fixture.detectChanges();
comp.ngAfterViewInit();
fixture.whenStable().then(() => {
input = fixture.debugElement.query(By.css("#inputId"));
inputEl = input.nativeElement;
});
});
});
Aucun commentaire:
Enregistrer un commentaire