I am trying to mock the mat-dialog which has ngoninit method ,in angular but it is not getting covered

136 Views Asked by At

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();
            });   }); });
1

There are 1 best solutions below

0
Nikhil Makwana On

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

    import { ComponentFixture, TestBed } from '@angular/core/testing';
    import { FormsModule } from '@angular/forms';
    import { MatDialog, MatDialogRef } from '@angular/material/dialog';
    import { AddPiecesComponent } from './add-pieces.component';
    import { CommonService } from 'src/app/shared/services/common.service';
    import { PieceManagementService } from 'src/app/shared/services/piece-management/piece-management.service';
    import { FormBuilder, FormGroup } from '@angular/forms';
    import { of } from 'rxjs';
    
    describe('AddPiecesComponent', () => {
      let component: AddPiecesComponent;
      let fixture: ComponentFixture<AddPiecesComponent>;
    
      let formBuilder: FormBuilder;
      let matDialog: MatDialog;
      let matDialogRef: MatDialogRef<AddPiecesComponent>;
      let pieceManagementService: PieceManagementService;
      let commonService: CommonService;
    
      beforeEach(() => {
        formBuilder = jasmine.createSpyObj('FormBuilder', ['group']);
        matDialog = jasmine.createSpyObj('MatDialog', ['open']);
        matDialogRef = jasmine.createSpyObj('MatDialogRef', ['close']);
        pieceManagementService = jasmine.createSpyObj('PieceManagementService', ['fetchAllZones', 'saveZones']);
        commonService = jasmine.createSpyObj('CommonService', ['openSnackBar']);
    
        TestBed.configureTestingModule({
          imports: [FormsModule],
          declarations: [AddPiecesComponent],
          providers: [
            { provide: FormBuilder, useValue: formBuilder },
            { provide: MatDialog, useValue: matDialog },
            { provide: MatDialogRef, useValue: matDialogRef },
            { provide: PieceManagementService, useValue: pieceManagementService },
            { provide: CommonService, useValue: commonService },
          ],
        });
    
        fixture = TestBed.createComponent(AddPiecesComponent);
        component = fixture.componentInstance;
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      describe('ngOnInit', () => {
        it('should call createPiecesForm and fetchAllZones', () => {
          spyOn(component, 'createPiecesForm').and.callThrough();
          spyOn(component, 'fetchAllZones').and.callThrough();
    
          component.ngOnInit();
    
          expect(component.createPiecesForm).toHaveBeenCalled();
          expect(component.fetchAllZones).toHaveBeenCalled();
        });
      });
    
      describe('createPiecesForm', () => {
        it('should create a FormGroup using FormBuilder', () => {
          const formGroup = jasmine.createSpyObj<FormGroup>('FormGroup', ['get']);
          const formControl = jasmine.createSpyObj('FormControl', ['setValue']);
          formGroup.get.and.returnValue(formControl);
          formBuilder.group.and.returnValue(formGroup);
    
          component.createPiecesForm();
    
          expect(formBuilder.group).toHaveBeenCalled();
          expect(component.pieceForm).toBe(formGroup);
          expect(component.pieceForm.get('nom')).toBe(formControl);
        });