0

I'm learning angular testing with jasmine and karma. I came across this showBanner() method in my project and don't know how to proceed further. This is a service method which creates a banner component with the given params and has ComponentFactoryResolver and ApplicationRef injected in the constructor.

I did some research but couldn't find any examples relating to this. How do I mock the constructor dependencies, specifically ApplicationRef. I read it somewhere that it is not necessary to mock ApplicationRef in the providers array in the testbed but I keep getting this error -> TypeError: Cannot read properties of undefined (reading 'instance') for the showBanner method line 1, which accesses the components property of appliationRef.

Here is the complete service method

import { ApplicationRef, ComponentFactoryResolver, Injectable, ViewContainerRef } from "@angular/core";
import { BannerComponent } from "src/app/components/banner/banner.component";
import { BannerSeverity } from "src/app/utils/utils";

@Injectable({
  providedIn: 'root'
})
export class BannerService {
  private resolver: ComponentFactoryResolver;                                 // Reference to component factory resolver
  banners : Array<any> = [];                                                  // Array to store all the banners

  /**
   * Constructor
   */
  constructor(
    resolver: ComponentFactoryResolver,
    private applicationRef: ApplicationRef) {
      this.resolver = resolver;
  }

  /**
   * Function called to show the banner with the specified configuration
   */
  public showBanner(severity: BannerSeverity, message: string, dismissible?: boolean, appendTo?: ViewContainerRef, moreInfo?: string ): void {
    let globalViewContainerRef = this.applicationRef.components[0].instance.viewContainerRef;
    let factory = this.resolver.resolveComponentFactory(BannerComponent);
    let component = null;
    if (appendTo) {
      component = appendTo.createComponent(factory);
    } else if (globalViewContainerRef) {
      component = globalViewContainerRef.createComponent(factory);
    }
    if (component) {
      let banner = component.instance;
      banner.severity = BannerSeverity[severity];
      banner.message = message;
      banner.dismissible = dismissible;
      banner.moreInfo = moreInfo;
      banner.dismissed.subscribe(() => {
        component.destroy();
      });
      this.banners.push(banner);
    }
  }
}

Here is my test file

import { ApplicationRef, ComponentFactoryResolver } from "@angular/core";
import { fakeAsync, flush, TestBed } from "@angular/core/testing";
import { BannerSeverity } from "src/app/utils/utils";
import { getTypicalSetup } from "src/testing/typical-setup";
import { BannerService } from "./banner.service";

/**
 * Test cases for banner service.
 */
describe('BannerService', () => {
  const mock = getTypicalSetup();
  let bannerService: BannerService;
  let BANNERS;
  let componentFactoryResolverSpy;

  /**
   * Run some shared setup before each of the specs.
   */
  beforeEach(fakeAsync(() => {
    componentFactoryResolverSpy = jasmine.createSpyObj<ComponentFactoryResolver>('ComponentFactoryResolver', ['resolveComponentFactory']);
    //Configure the test bed.
    TestBed.configureTestingModule({
      imports: [...mock.imports],
      providers: [
        ...mock.providers,
        BannerService,
        { provide: ComponentFactoryResolver, useValue: componentFactoryResolverSpy },
      ],
    });
    bannerService = TestBed.inject(BannerService);
    //Banners array with wasDismissed property.
    BANNERS = [
      { wasDismissed: false },
      { wasDismissed: false },
    ];
  }));

  /**
   * Test to ensure the service is created.
   */
  it('should be created', () => {
    expect(bannerService).toBeDefined();
  });

  /**
   * Test to ensure that the showBanner method creates a banner
   * based on various parameters.
   */
  describe('#showBanner', () => {
    it('should create a banner with severity and message parameters passed', fakeAsync(() => {
      //Arrange
      const severity: BannerSeverity = BannerSeverity.critical;
      const message: string = "Test Message";

            //Act
      bannerService.showBanner(severity, message);
            flush();

            //Assert
      expect(bannerService.banners[0]).toBeDefined();
        }));
  });
});

1 Answer 1

0

You can maybe mock it the same way as ComponentFactoryResolver.

import { ApplicationRef, ComponentFactoryResolver } from "@angular/core";
import { fakeAsync, flush, TestBed } from "@angular/core/testing";
import { BannerSeverity } from "src/app/utils/utils";
import { getTypicalSetup } from "src/testing/typical-setup";
import { BannerService } from "./banner.service";

/**
 * Test cases for banner service.
 */
describe('BannerService', () => {
  const mock = getTypicalSetup();
  let bannerService: BannerService;
  let BANNERS;
  let componentFactoryResolverSpy: jasmine.SpyObj<ComponentFactoryResolver>;
  // add this line
  let applicationRefSpy: jasmine.SpyObj<ApplicationRef>;

  /**
   * Run some shared setup before each of the specs.
   */
  beforeEach(fakeAsync(() => {
    componentFactoryResolverSpy = jasmine.createSpyObj<ComponentFactoryResolver>('ComponentFactoryResolver', ['resolveComponentFactory']);
    // mock how you like
    applicationRefSpy = jasmine.createSpyObj<ApplicationRef>('ApplicationRef', {}, { components: [{ instance: { viewContainerRef: {} } }] });
    //Configure the test bed.
    TestBed.configureTestingModule({
      imports: [...mock.imports],
      providers: [
        ...mock.providers,
        BannerService,
        { provide: ComponentFactoryResolver, useValue: componentFactoryResolverSpy },
        // add mock
        { provide: ApplicationRef, useValue: applicationRefSpy },
      ],
    });
    bannerService = TestBed.inject(BannerService);
    //Banners array with wasDismissed property.
    BANNERS = [
      { wasDismissed: false },
      { wasDismissed: false },
    ];
  }));

  /**
   * Test to ensure the service is created.
   */
  it('should be created', () => {
    expect(bannerService).toBeDefined();
  });

  /**
   * Test to ensure that the showBanner method creates a banner
   * based on various parameters.
   */
  describe('#showBanner', () => {
    it('should create a banner with severity and message parameters passed', fakeAsync(() => {
      //Arrange
      const severity: BannerSeverity = BannerSeverity.critical;
      const message: string = "Test Message";

            //Act
      bannerService.showBanner(severity, message);
            flush();

            //Assert
      expect(bannerService.banners[0]).toBeDefined();
        }));
  });
});

Check out this link: https://stackoverflow.com/a/64560773/7365461 on how to mock properties with createSpyObj.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.