Below is my ts file which I am trying to unit test which has mat-dialog and I am creating a form, till constructor code is getting covered but rest of the method I am unbale to call.Below is my spec file where I have mocked mat-dialog, forms module and my service and trying to mock ngoninit method.
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog,MatDialogRef } from '@angular/material/dialog';
import { PieceManagementService } from 'src/app/shared/services/piece-management/piece-management.service';
import { CommonService } from 'src/app/shared/services/common.service';
import { commonConstants } from 'src/app/shared/utils/constant';
@Component({
selector: 'app-add-pieces',
templateUrl: './add-pieces.component.html',
styleUrls: ['./add-pieces.component.scss']
})
export class AddPiecesComponent implements OnInit {
selectedPieces:any = [];
pieces:any = [];
errorPiece : string;
empForm: FormGroup;
pieceName:any;
nom:any;
errorMessage:string;
public pieceForm: FormGroup;
public pieceValidationMessages = commonConstants.pieceValidationMessages;
constructor(private _fb: FormBuilder, private pieceManagement:PieceManagementService,
public dialogRef: MatDialogRef<AddPiecesComponent>, private commonService:CommonService) {
}
ngOnInit(): void {
this.createPiecesForm();
this.fetchAllZones();
}
public fetchAllZones(){
this.pieceManagement.fetchAllZones().subscribe((response: any) => {
response.forEach((item)=>{
return item.active = false;
})
this.pieces = response;
console.log(this.pieces);
});
}
createPiecesForm(){
this.pieceForm = this._fb.group({
nom: ['',Validators.required]
});
}
activateClass(subModule){
subModule.active = !subModule.active;
subModule.activeli = !subModule.activeli;
if (this.selectedPieces.length === 0 && subModule.active === true){
this.selectedPieces.push(subModule);
} else {
let index = this.selectedPieces.findIndex((piece) => piece.zoneId === subModule.zoneId);
if (subModule.active === true && index === -1) {
this.selectedPieces.push(subModule);
}
if (subModule.active === false && index >= 0) {
this.selectedPieces.splice(index, 1);
}
}
}
createTest(){
if(this.selectedPieces.length == 0){
this.errorMessage = "Please select zone";
}
else if (this.pieceForm.valid){
const param ={
"pieceName":this.pieceForm.controls.nom.value,
"selectedZoneList":this.selectedPieces
}
this.pieceManagement.saveZones(param).subscribe((response: any) => {
this.commonService.openSnackBar('Piece have been added successfully!')
this.dialogRef.close({event:'add'});
});
}
}
close(){
this.dialogRef.close({event:'cancel'})
}
}
component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { AddPiecesComponent } from './add-pieces.component'; import { NO_ERRORS_SCHEMA } from "@angular/core"; import { FormBuilder } from "@angular/forms"; import { MatDialog, MatDialogRef } from "@angular/material/dialog"; import { FormsModule } from "@angular/forms"; import { CommonService } from 'src/app/shared/services/common.service'; import { PieceManagementService } from 'src/app/shared/services/piece-management/piece-management.service';
describe('AddPiecesComponent', () => { let component: AddPiecesComponent; let fixture: ComponentFixture<AddPiecesComponent>; beforeEach(() => {
const formBuilderStub = () => ({ group: object => ({}) });
const matDialogStub = () => ({});
const matDialogRefStub = () => ({ close: object => ({}) });
const pieceManagementServiceStub = () => ({
fetchAllZones: () => ({ subscribe: f => f({}) }),
saveZones: param => ({ subscribe: f => f({}) })
});
const commonServiceStub = () => ({ openSnackBar: string => ({}) });
TestBed.configureTestingModule({
imports: [FormsModule],
schemas: [NO_ERRORS_SCHEMA],
declarations: [AddPiecesComponent],
providers: [
{ provide: FormBuilder, useFactory: formBuilderStub },
{ provide: MatDialog, useFactory: matDialogStub },
{ provide: MatDialogRef, useFactory: matDialogRefStub },
{
provide: PieceManagementService,
useFactory: pieceManagementServiceStub
},
{ provide: CommonService, useFactory: commonServiceStub }
]
});
fixture = TestBed.createComponent(AddPiecesComponent);
component = fixture.componentInstance; });
it('can load instance', () => {
expect(component).toBeTruthy(); });
it(`selectedPieces has default value`, () => {
expect(component.selectedPieces).toEqual([]); });
it(`pieces has default value`, () => {
expect(component.pieces).toEqual([]); });
describe('ngOnInit', () => {
it('makes expected calls', () => {
spyOn(component, 'createPiecesForm').and.callThrough();
spyOn(component, 'fetchAllZones').and.callThrough();
component.ngOnInit();
expect(component.createPiecesForm).toHaveBeenCalled();
expect(component.fetchAllZones).toHaveBeenCalled();
}); }); });
Write your unit tests using Jasmine's test methods. Here's an example of how you can modify your test file to test the AddPiecesComponent component