Angular: Troubleshooting - potential bug in test case with jasmine causing TypeError: Undefined property 'cmd' OrAngular: Debugging

I'm working on writing a unit test case for integrating lotame analytics. Can anyone offer some assistance on how to write a test case for this integration? I've been stuck on this for quite some time now and keep receiving

TypeError: Cannot read property 'cmd' of undefined
.

app.ts

declare global {
  interface Window {
    lotame_123: {
      cmd: any;
      collect: any;
    };
  }
}

export const collectLotameData = (title: string, name: string) => {
  window.lotame_123.cmd.push(function () {
    window.lotame_123.collect({
      behaviors: {
        act: [`tracking : ${title} : ${name}`]
      }
    });
  });
};

app.spec.ts

describe('collectLotameData', () => {
  beforeEach(() => {
    window.lotame_123 = {
      cmd: 'sdas',
      collect: 'any'
    };
  });
});

Answer №1

To effectively monitor and track the activities related to window.lotame_123.cmd.push() and window.lotame_123.collect() methods, it is recommended to create a spy. By implementing the cmd.push() method, we can intercept the function passed in test cases and assign it to fnRef for future execution. Subsequently, by executing the fnRef function, we can conduct tests on the window.lotame_123.collect() method.

Below are the specified test cases:

app.ts:

declare global {
  interface Window {
    lotame_123: {
      cmd: any;
      collect: any;
    };
  }
}

export const collectLotameData = (title: string, name: string) => {
  window.lotame_123.cmd.push(function () {
    window.lotame_123.collect({
      behaviors: {
        act: [`tracking : ${title} : ${name}`],
      },
    });
  });
};

app.spec.ts:

import { collectLotameData } from './app';

fdescribe('collectLotameData', () => {
  it('should pass', () => {
    const cmdSpy = jasmine.createSpyObj('cmd', ['push']);
    let fnRef;
    cmdSpy.push.and.callFake((fn) => {
      fnRef = fn;
    });
    const collectSpy = jasmine.createSpy();

    window.lotame_123 = {
      cmd: cmdSpy,
      collect: collectSpy,
    };
    collectLotameData('best singer', 'teresa teng');
    expect(cmdSpy.push).toHaveBeenCalledWith(jasmine.any(Function));
    fnRef();
    expect(collectSpy).toHaveBeenCalledWith({
      behaviors: {
        act: [`tracking : best singer : teresa teng`],
      },
    });
  });
});

Test results: https://i.sstatic.net/rSzFJ.png

Source code: https://github.com/mrdulin/angular-v11-codelab/tree/master/src/app/examples/98765432

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the Inline Partial<T> object still throwing errors about a missing field?

I recently updated to TypeScript version ~3.1.6 and defined an interface called Shop as follows: export interface Shop { readonly displayName: string; name: string; city: string; } In this interface, the property displayName is set by the backend a ...

Type inference and the extends clause in TypeScript 4.6 for conditional types

My focus was on TypeScript 4.7 when I created the following types: const routes = { foo: '/foo/:paramFoo', bar: '/bar/:paramFoo/:paramBar', baz: '/baz/baz2/:paramFoo/:paramBar', } as const; type Routes = typeof routes; ...

Exploring the depths of useDispatch and dispatch in React-Redux

I am currently analyzing the code written by a former colleague of mine. Based on my understanding, useDispatch accepts an object containing the action type and payload, which is then compared to all reducers to update the state accordingly. However, in t ...

"Encountering an error when trying to access a non-existent property in a Jasmine test with

I have been tasked with working on a client's legacy codebase, specifically a node.js project for Jasmine tests. The issue I'm running into is that when I execute the test, the function being called from a different file cannot access certain met ...

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

Having trouble transferring sound files to Cloudinary API through javascript

I have successfully implemented a function in my React Native application to upload images to Cloudinary. Now, I am trying to modify the function to upload audio files as well. Despite specifying the "resource_type" parameter as "raw", "video", or "auto", ...

If the table spans multiple pages, a top margin will be added to ensure proper formatting. This feature is implemented using jspdf-autotable

I have encountered an issue with my PDF function where using multiple tables and the didDrawPage() hook to add headers and footers results in images being drawn multiple times in the header due to the multiple tables. To resolve this, I created a separate ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

"Encountering a 'module not found' error while trying to execute unit tests in Node.js, where React is a peer dependency in a

Here is the structure of my app: App A App B Common package Both App A and App B have included the common package in their package.json: { dependencies: { "commonPackage": "file:../../../commonPackage" } } React is being used by both apps an ...

Configuring Stylelint in a NextJS project using Emotionjs

I recently encountered an issue while trying to integrate Stylelint into a new NextJS Typescript project with EmotionJS. Many rules were not working in my styles files, and the only error I could identify was Unknown word CssSyntaxError. This particular U ...

Hovering over a table cell triggers a popup in Angular

Inserted a class into <td><span class="only-show-on-hover"></span></td> CSS code for the class td span.only-show-on-hover { visibility: hidden; } td:hover span.only-show-on-hover { visibility: visible; } Code for dialog box < ...

Disabled controls within Angular 2 forms are not factored into the form.value output

One thing I've observed is that with Angular 2 reactive forms, if a control is disabled then it won't be included in the form.value. For example, consider this form definition: this.notelinkingForm = new FormGroup({ Enabled: new FormControl( ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Is it possible to bind an http post response to a dropdown list in Angular?

My goal is to connect my post response with a dropdown list, but the text displayed in the drop-down box shows "[object Object]". My request returns two results - `ArticleID` and `Title`. I want to display `Title` in the dropdown and save the corresponding ...

Sorting an array of objects in TypeScript may result in a type error

My data includes various categories, ages, and countries... const data = [ { category: 'Fish', age: 10, country: 'United Kingdom' }, { category: 'Fish', age: 9, country: 'United Kingdom' }, { category: ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

What is preventing me from retrieving the data accurately? (Angular)

I'm currently facing an issue with a specific part of the application I'm developing: This is how the component's logic works: export class StockStatusComponent implements OnInit{ articles: Article[] = []; selectedLevel: any; constr ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Is there a way to conceal the progress output of an Angular build during test execution using Karma?

Currently, I am setting up a build process for an Angular 4 application and aiming to prevent progress output in order to keep the runner's logs clean. The project configurations were automatically created using angular cli (v1.0.1) By utilizing ng ...

Error: The value associated with the key 'services.authentication.basic.user.service' is not defined in the current context, causing a ResolutionError with a code of

I have been working on creating custom authentication using LoopBack 4. I referred to the following documentation: services.authentication.basic.user.service is showing as not bound. This pertains to the user.controller where I've injected JWTAuthen ...