Search code examples
angulartypescriptkarma-jasminekarma-coverage

Karma Testing Angular - this.alertService.danger is not a function


When i'm trying test using karma, the issue showing..

TypeError: this.alertService.danger is not a function

Here is my Component,

import { Component, OnInit, ViewChild, ElementRef, AfterViewChecked } from '@angular/core';
import { Router  } from '@angular/router';
import { ApiService } from '../services/api.service';
import { NgxSpinnerService } from "ngx-spinner";
import { AlertService } from 'ngx-alerts';

@Component({
  selector: 'app-review',
  templateUrl: './review.component.html',
  styleUrls: ['./review.component.scss']
})
export class ReviewComponent implements OnInit  {
  @ViewChild('scrollMe', { read: ElementRef }) public scroll: ElementRef;
  @ViewChild('scrollMe', { read: ElementRef }) public scrollbottom: ElementRef;

  cartDetails: any;
  cartId:any;
  menuItems:any;
  expectedDeliveryTime:any
  noOfNulls: any;

  constructor(
    public router: Router,
    public apiService: ApiService,
    private alertService: AlertService,
    private spinner: NgxSpinnerService) { 
    this.spinner.show();
    this.cartId = localStorage.getItem('cartId');
    
    if(!this.cartId){
      
      this.noOfNulls = localStorage.getItem('noOfNulls');
    
      if(!this.noOfNulls){
        localStorage.setItem('noOfNulls','1')
        this.alertService.danger("Please add at least one product to the cart.");
        this.changeSomething();
      } else if(this.noOfNulls==1) {
        localStorage.setItem('noOfNulls','2');
        this.alertService.danger("Please add at least one product to the cart.");
        this.changeSomething();
      }
      else{
        localStorage.setItem('noOfNulls','')
        this.router.navigate(['home']);
      }


    } 

  }

  ngOnInit(): void {
    this.apiService.getCartDetais(this.cartId).subscribe((res)=>{
      this.spinner.hide();
      this.cartDetails = res.body.cart;
      this.menuItems = res.body.cart.menuItems;

      this.expectedDeliveryTime = res.body.expectedDeliveryTime;
      localStorage.setItem('expectedDeliveryTime',this.expectedDeliveryTime)

    });
    

  }

  confirm() {
    this.router.navigate(['subscription']);
  }

  goBack() {
    localStorage.setItem('val','0');
    this.router.navigate(['product']);
  }

  cancel() {
    this.router.navigate(['home'])
  }
  
  changeSomething(){
    localStorage.setItem('val','0');
    this.router.navigate(['product']);
    
  }


  

}

spect.ts,

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ReviewComponent } from './review.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClient, HttpClientModule, HttpHandler } from '@angular/common/http';
import { FormBuilder } from '@angular/forms';
import { AlertService } from 'ngx-alerts';
import { TestAlertService } from '../services/test-alert.service';

describe('ReviewComponent', () => {
  let component: ReviewComponent;
  let fixture: ComponentFixture<ReviewComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ReviewComponent ],
      imports: [RouterTestingModule,HttpClientModule],
      providers: [
        HttpClient,
        FormBuilder,
        HttpHandler,
        { 
          provide: AlertService, 
          useClass: TestAlertService 
        }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ReviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Thanks.......................................................................................................................................................................................................................................


Solution

  • It should have function danger in your TestAlertService. Try to create Mock Class in specs only.

    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    
    import { ReviewComponent } from './review.component';
    import { RouterTestingModule } from '@angular/router/testing';
    import { HttpClient, HttpClientModule, HttpHandler } from '@angular/common/http';
    import { FormBuilder } from '@angular/forms';
    import { AlertService } from 'ngx-alerts';
    
    export class TestAlertService {
      danger() {
        console.log("Danger Alert")
      }
    }
    
    describe('ReviewComponent', () => {
    let component: ReviewComponent;
    let fixture: ComponentFixture<ReviewComponent>;
    
    beforeEach(async(() => {
        TestBed.configureTestingModule({
        declarations: [ ReviewComponent ],
        imports: [RouterTestingModule,HttpClientModule],
        providers: [
            HttpClient,
            FormBuilder,
            HttpHandler,
            { 
            provide: AlertService, 
            useClass: TestAlertService 
            }
        ]
        })
        .compileComponents();
    }));
    
    beforeEach(() => {
        fixture = TestBed.createComponent(ReviewComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    
    it('should create', () => {
        expect(component).toBeTruthy();
    });
    });
    

    It should Work for you.