0

I am unit testing my component which uses a external javascript library, I am importing and initializing the libary in my component.ts All my test cases work fine if I comment the line aksService = aksServiceFactory(); (code below) but it gives a error TypeError: Cannot read properties of undefined (reading 'AKS') if i uncomment it. I tried importing the library in spec.ts file also but it gives same error.

I want to include this library in my component.spec.ts file so it doesnt give me this error or if there is a way can we exclude this file from unit test so it doesnt give this error.

component.ts file

import { aksServiceFactory } from '../../services/gdl.service';
import { GlobalConstants } from '../../global-constants';


@Component({
  selector: 'app-page',
  templateUrl: './opt-page.component.html',
  styleUrls: ['./opt-page.component.scss']

})

export class OptPageComponent implements OnInit {

  //initialize aks Service

  aksService = aksServiceFactory();

aks.service.ts

// aks.service.js

export const aksServiceFactory = () => {
    const aksQueue = window.cms.aks;
    const sendPageview = (pageId) => {
      aksQueue.push(['event:publish', ['page', 'pageinfo']]);
    };

    const sendEvent = (category, name, payload) => {
      aksQueue.push(['event:publish', [category, name, payload]]);
    };

    const enableDebugMode=()=>{
      aksQueue.debug.enable();
    }

    return {
      enableDebugMode,
      sendPageview,
      sendEvent,
    };
  };
blume0F
  • 65
  • 2
  • 10

1 Answers1

0

Create the service with dependency injection and mock it. The unit test should not rely on external libs only if it is neccessary you have to test the functionality of the component, so when you mock it you have to return the mocked service with the correct return values. This will garantee that if the library change the unit test will not fail. :) These articles will help to you:

How to mock service function in Angular component for unit test

https://angular.io/guide/dependency-injection-providers#using-factory-providers

  • Thanks @Zsombor for the answer, actually i dont need to test any single line of code from this library, but its usage and initialization is breaking my main component test cases – blume0F Apr 24 '22 at 12:16