Experimenting with code within a window event listener function

I have a component in my AngularJS application that is functioning correctly. However, when it comes to test coverage, everything after the 'window.addEventListener('message',' part is not being covered.

Should I create a mock object for the 'window' and provide my own implementation for 'addEventListener', or should I spy on it and verify that it has been called?

Here is the code for my.component.controller.ts:

export class MyComponentController {
  constructor() {}

  public theEventOccurred(e: any) {
    let json = JSON.parse(e.data);
    console.log(json.document);
  }

  public $onInit() {
    window.addEventListener('message', (event) => {
      this.theEventOccurred(event);
    }, false);
  }
}

And here is the testing file code in my.component.spec.ts:

describe('Component: my', () => {

  let $componentController: angular.IComponentControllerService;
  let scope: angular.IScope;

  beforeEach(inject(
    ($rootScope: angular.IScope,
      _$componentController_: angular.IComponentControllerService) => {
      scope = $rootScope.$new();
      $componentController = _$componentController_;
    }));

  describe('Controller: MyComponentController', () => {
    it('should log json.document', () => {
      let ctrl: any = $componentController('my', { $scope: scope });
      ctrl.$onInit();
    });
  });
});

Answer №1

In my opinion, it's not advisable to directly access the window or document object from within the component code.

A better approach would be to encapsulate the window in a separate service and then utilize dependency injection to include the service in the component.

You can refer to this resource for an example.

This way, you'll be able to test the service methods independently or substitute a mock service during testing.

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

What is the method to permanently install and enforce the latest version using npm?

We are implementing a private npm module for exclusive use within our organization. Given that the module is managed internally, we have confidence in version updates and changes. Is there a way to seamlessly install this module across multiple projects s ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Exploring the power of Partial Views in ASP.NET MVC 4 with Ajax.ActionLink

On my homepage, I am attempting to incorporate links that will render partial views - revealing information from the database when clicked. I want the link to be replaced by text on the same page. Despite following a tutorial, I am facing challenges in get ...

Compiling with GatsbyJs throws an abrupt token error with 'if' being an unexpected token

I am working on a code snippet in GatsbyJS where I am extracting data from a StaticQuery using GraphQL and then rendering a component. The challenge I am facing is to conditionally check if a specific sub-object exists within the data object, and if it doe ...

Instructions for user to upload and play an MP4 file on their PC

For my web project that utilizes node.js, HTML, and JavaScript, I am looking to incorporate a video player element. I want users to have the ability to click a button and play an MP4 file directly on the webpage. How can I achieve this? I currently have s ...

Tips for sending information from PHP to an AJAX function

Hello, I am in the process of learning PHP and I am attempting to retrieve data from a PHP file using the script below. However, I am not receiving any response: $.ajax({ type: 'POST', url: "mark_mod.php", ...

Issues encountered when incorporating personalized CSS into a Vuetify element

Working with the Vuetify selector input component, v-select, and wanting to customize its style led me to inspecting it in Chrome and copying down the necessary classes. For instance, to change the font size of the active value, I utilized: .v-select__sel ...

Why is the Javascript code outputting undefined and NaN during execution?

As a newcomer to the world of javascript, I am venturing into learning its fundamental concepts. In my quest for knowledge, I've dabbled in file reading and came up with a small script which you can find below. // Incorporating the fs (filesystem) mo ...

Looking to dynamically load ng-model within an ng-repeat for a set of radio buttons

I am trying to dynamically load ng-model with data from an API call using ng-repeat for a series of radio buttons" This is my Controller: angular.module('app').controller('apiCallController', [$scope,'$http',function($scope, ...

Modification of text within a text field via a context menu Chrome Extension

Currently, I am embarking on my first endeavor to create a Chrome extension. My goal is to develop a feature where users can select text within a text field on a website using their mouse and have the ability to modify it by clicking on a context menu. Be ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

Discovering if an ID already exists in a Firebase real-time database with React.js

Currently, I am engaged in a React inventory project. In order to avoid duplication when pushing data into the progress.json file, I need to ensure that the data is not already present by checking for the unique id associated with each dataset. Despite m ...

Improving file reading and parsing efficiency with fast random access using csv-parse in Node.js

I recently encountered a challenge while working with the csv-parser library in node for parsing large CSV files. The files I work with can range from 50,000 to 500,000 lines or even larger. My task involved performing computations on this data and then su ...

Trouble updating outside controller data while using AngularJS directive inside ng-repeat loop

I am currently working with a isolate scope directive that is being used inside an ng-repeat loop. The loop iterates over an array from the controller of the template provided below: <!DOCTYPE html> <html> <head> <link rel="sty ...

An error occurred as the Serverless Function timed out while attempting to load a dynamic route in Next.js version 13

I have a basic Next.js application with the following route structure: /contentA/ - Static - Initial load: 103 kB /contentA/[paramA]/groups - SSG - Initial load: 120 kB /contentB/[paramA]/[paramB]/[paramC] - SSR (client component) - Initial load: 103 kB ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

Is it possible to utilize an API response within a conditional statement in NextJS?

I am working on a change password feature that interacts with an API for verification. If the current password entered is incorrect, I want to display an error message. If you have any suggestions on how to proceed or if there are any flaws in my approach ...

Steps for displaying an HTML table in Excel by clicking on a button

My goal is to open an HTML table in XLS format with a single click of a button. Currently, I have a JavaScript function that allows me to export the HTML table to XLS using the "save as" option. However, I want to enhance this functionality so that clickin ...

HTML content that is produced through JSONP retrieval

Recently, I've been experimenting with the jQuery library and have found it to be quite useful. Lately, I've been delving into AJAX requests to fetch various information like weather updates, current downloads, and more, which has been going smoo ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...