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

Adding names in real time to a list within a template

I am currently facing an issue while attempting to dynamically add and populate values in an array. Strangely, I am unable to see any output from a console.log statement. This has left me perplexed as to why there are no errors or logs being displayed. Co ...

Detach an item from its parent once it has been added to an array

Currently, I am facing an issue with a form on my blog. The blog is represented as an object that contains multiple content objects within it. I seem to be experiencing some confusion because the reactivity of the content I add to the Array persists with t ...

The behavior of Elementor lightbox buttons upon being clicked

When using Android, I've noticed that the lightbox briefly displays a semitransparent cyan bar on the left and right buttons when they are pressed. Is there a way to control or prevent this behavior? Any suggestions would be appreciated! Thanks in adv ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Every time I try to set up the MailChimp pop-up javascript, I encounter an Uncaught Error message saying that Bootstrap tooltips need Tether and an Uncaught ReferenceError message

Utilizing Wordpress and Understrap. Upon inserting the following code: <script type="text/javascript" src="//downloads.mailchimp.com/js/signup- forms/popup/embed.js" data-dojo-config="usePlainJson: true, isDebug: false"> </script><script ty ...

I'm looking for a design that features larger font size for the number before the decimal point compared to the numbers that follow it

Is there a way to achieve different font sizes for the numbers before and after the decimal point using AngularJS, similar to what can be done with jQuery by assigning classes? .tdSplit { text-align: right; } .tdGreen { font- ...

Using JQuery to delete an item by clicking on the delete button and then clicking on the item to remove it

I am currently using jQuery to dynamically create items on an HTML canvas for users to drag around and create drawings in a style similar to Microsoft Visio. However, I am struggling with how to remove these items once they have been created. While I know ...

How to Troubleshoot jQuery AJAX Not Sending JSON Data

I've been attempting to make an ajax request, but it keeps returning with an error response. $('form#contactForm button.submit').click(function () { var contactName = $('#contactForm #contactName').val(); ...

Automatically close an element when you click on a different element

Hello everyone! I need some help again. I'm working on a script that displays an overlay when a menu item is clicked. Within this menu, there is a modal contact form with a close icon or anchor that should appear when clicked. My goal is to have the o ...

Having trouble getting data to send to node.js server using $.ajax post

Trying to convert a table date into an array and send it to the server side using Ajax post for the first time. Despite following all the suggestions in previous posts, I am still struggling. Utilizing body-parser to extract data on the server side. Any he ...

Angular2: Leveraging click events to manage CSS classes on elements

I am currently developing a web app using Angular 2. I'm facing an issue where the active element should receive an extra CSS class when clicked, but adding the ":active" CSS attribute with a custom class doesn't work as expected. The ":focus" pr ...

Javascript - Incorporate a hyperlink into my Flickr Api image query

I am struggling with incorporating a link around the image generated by this request due to my limited API knowledge. Below is the current function responsible for displaying the album images. To see a functional version, please refer to the provided fidd ...

JSON has encountered an unconventional string at position 41 that was not anticipated

Attempting to learn Javascript as a beginner, I am facing an error that is puzzling me: SyntaxError: /home/runner/myrepl/config.json: Unexpected string in JSON at position 41 Upon checking my index.js file, it seems correct at position 41 (at least I beli ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Encountering issues in transmitting form data to a Node server from Angular

In my Angular application, I am working on creating a registration page with validation. Once the user fills out the form and submits it, the data is sent to the server and saved in MongoDB. This is the approach I have taken: register_user() { const ...

Utilizing AJAX to showcase an HTML popup

I am currently working on a project to create an HTML page that will display another HTML file in an alert when a button is pressed. However, I am facing an issue where the content is not being displayed as expected. <html> <head> ...

It vanishes as soon as you move your cursor away during the animation

I created a button component with text animation, but I'm encountering an issue. When I hover over the button, the animation works smoothly. However, if I quickly move my cursor away or unhover in the middle of the animation, the text disappears unex ...

Issue: Unable to reach essential Node.js modules

After attempting to deploy Next.js on Cloudflare Pages, I encountered the following error: Error: Could not access built-in Node.js modules. It is recommended to ensure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag ...

Submitting alterations to the server with AngularJS: Utilizing $resource for POST requests

I'm having issues with a particular AngularJS problem. On the server, I have a model stored in a .json file: { feedback: [] } The goal is to collect user input from a form and add it to the feedback array as individual javascript objects. I at ...