Angular custom window injection

Currently, I am working on an Angular application that is housed within an Android WebView. To facilitate communication with my Android application, I have made an object accessible at the window level:

window.MyAndroidApp

This object contains various methods such as:

window.MyAndroidApp.doStuff();
window.MyAndroidApp.doOtherStuff();

I find myself unsure of how to interact with this object through an Angular controller without directly referencing it. This way, I can easily mock it for unit testing purposes.

// How can I set androidFunctions as a reference to window.MyAndroidApp so that
// I can mock it during unit testing?
app.controller("MyCtrl", ["$scope", "androidFunctions", function($scope, androidFunctions) {
    androidFunctions.doStuff();
    androidFunctions.doOtherStuff();
}]);

Answer №1

Transform this into a feature - then you can simulate it traditionally.

angular.module('myApp').factory('androidManager', [$window, function ($window) {
   return $window.MyAndroidApp;
});

By placing it on the window object, you can also access it through $window and mock it using tools like sinon.

sinon.mock($window, 'MyAndroidApp', {
   doStuff: function () {....},
   doOtherStuff: function () {..}
});

Answer №2

Utilize the angular $window service in your development process.

Information from official documentation:

The $window service is a reference to the browser's window object. While JavaScript globally has access to window, using it directly can lead to testability issues due to its global nature. In Angular, we make use of the $window service instead, allowing it to be overridden, removed, or mocked for testing purposes. https://docs.angularjs.org/api/ng/service/$window

<script>
  angular.module('windowExample', [])
    .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
      $scope.greeting = 'Hello, World!';
      $scope.doGreeting = function(greeting) {
        $window.alert(greeting);
      };
    }]);
</script>

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

No data, response or issue received from the Internet API

In my web api project, I have created the following controller: public IEnumerable<Speciality> GetAllSpecialities() { List<Speciality> specialities = null; try { specialities = (new Datatable(Proper ...

dynamically loading jQuery scripts and content via ajax

I have a webpage that displays a file tree with links to different pages and subfolders. The folders are getting too large, so I want to use a jQuery script to hide them. However, the issue is that the tree is loaded dynamically through ajax, so the jQuery ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

Incorporating external content to make it easily discoverable by Google for optimal SEO performance

I am currently working on a project that involves loading external content onto a customer's site. Our main goal is to provide the customer with a simple inclusion method, such as a one-line link similar to Doubleclick, without requiring any server-si ...

Encountered an npm installation error: The rollbackFailedOptional issue arose during the npm session with the verb npm-session a0d68 while attempting the command npm install --save

Every time I attempt to install babel, I encounter the following error message: rollbackFailedOptional: verb npm-session a0d68 The version of Node currently installed is 12.16.1 The version of npm being used is 6.13.4 All I want is to get babel up and ...

How can I start the Jitsi Meet app on my phone using a QR code?

For an upcoming event, participants will be walking around with mobile phones scanning QR codes to enter face-to-face chats with distant participants on laptops using Jitsi Meet as the video chat application. Since the users will be pre-registered, they ...

Converting long date format to short date format: yyyy-mm-dd

Is there a way to convert the long date format from "Sat Dec 13 2014 06:00:00 GMT+0600" to "2014-12-13" in yyyy-mm-dd format? <script> function myDate(val) { var now = new Date("<?php echo $Cnextdue;?>"); now.setDate(now.getDate() + 30*val); ...

Is it acceptable to include the bundled main.js file in the gitignore for a HUGO project?

Is it possible to exclude the bundled main.js file from a HUGO project by adding it to .gitignore? ...

Angular II slash avoiding Pipe

I am working on developing a customized pipe in Angular 2 that will handle the replacement of the backslash ('\') character in a given string. This backslash is commonly used to escape special characters. What I have accomplished so far: T ...

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

Why is my nested React Router component failing to load upon page refresh?

Lately, I have been delving into learning react and for the past few weeks. However, I've encountered an issue where when I try to reload the page using the browser's reload button, instead of reloading the component, it simply disappears (turnin ...

Error Message: React encountered an issue when trying to access the 'theme' property of an undefined object

Currently developing a web application using React, I encountered an issue when trying to implement the react-datepicker component in my code. Upon adding the following lines of code, my web application breaks and an error is thrown: import {SingleDatePic ...

Tips for retrieving the MenuItem name upon click event using Menu and MenuItem components in Material UI React

Utilizing MaterialUI's Menu and MenuItem components in a React project, I am looking to display the name of the menu item upon clicking on it. Upon inspecting event.currentTarget in console.log, it returns the entire list item: ListItem Image attache ...

Angular q.all: comparing immediate and delayed responses

Seeking advice on methodology: I currently utilize $q.all to handle multiple promises in a single return, processing all results as one request. For instance: $q.all([promise1(),promise2(),promise3(),promise(4),promise5()])..then(function(response){ ...} ...

Halting a function within a specific namespace

Is there a way to prevent certain characters from being entered during a keypress event for inputs when using a namespace in JavaScript? I noticed that even if the function returns false when the character is detected, the character still gets entered. How ...

What is the process for browserifying the net.Socket module in Node.js?

I'm exploring ways to connect and query my MS SQL database from JavaScript in a web browser (specifically Chrome, not IE as I don't want to use ActiveX controls). I came across this Node library called Tedious and Browserify to help with this tas ...

Terminate the npm build script within a Node.js script

I have developed a node script that checks for the presence of a lock file in my project. If the lock file is not found, I want to stop the npm build process. Any suggestions on how to achieve this? lock-check.js const path = require('path'); c ...

Ways to check if a user is logged in on a mobile application

As I embark on creating my very first mobile app with user login functionality, I find myself at a crossroads when it comes to determining the best way to store the logged-in status. The app will interact with backend webservices on my website, allowing u ...

Locate MongoDB documentation pertaining to arrays of objects with two specific fields

For instance, consider a Mongo db collection: [ { "user_id": 1, "lead_id": 901, ... ... }, { "user_id": 2, "lead_id": 902, ... ... }, { "user_id": 2, & ...

Encountering the message "Error: Unable to access undefined properties (reading 'username')" while making my POST request

My POST request isn't functioning correctly and it's failing to update. The specific error message I'm encountering is: TypeError: Cannot read properties of undefined (reading 'username') app.post('/create-user', functio ...