'Angular Excluding external javascript library from unit testing

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,
    };
  };


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zsombor Szende