Jasmine spying on a standalone function that is not a method of an object

What is the best way to spy on a function that is not a method of an object? In my specific case, the function callMe is not defined on the window object - it is a dependency loaded through angular.

if (X) {
  callMe('hello');
}

Answer №1

One way to create a spy object is by using the jasmine.createSpy method. This spy object, being a regular JavaScript object, can be utilized to replace your existing callMe function for the purpose of monitoring its behavior.

function callMe() {
    // implementation
}

describe('an example block', function() {
    it('creates a spy', function() {
        callMe = jasmine.createSpy('callMe');
        callMe();
        expect(callMe).toHaveBeenCalled();
    });
});

According to the Jasmine 2.5 documentation:

When no specific function is available to be spied on, jasmine.createSpy can generate a "bare" spy. This type of spy behaves like any other spy — keeping track of calls, arguments, etc. However, there is no underlying implementation associated with it. Spies are essentially JavaScript objects that can be manipulated as such.

Answer №2

If you want to inject a spy into your controller, you can create it and then pass it in. Take a look at this example:

beforeEach(
        inject(function (_$controller_) {
            myController = _$controller_('myControllerName', {
                callMe: jasmine.createSpy('callMe');
            });
        })
    );

By using this approach, the callMe object will be replaced with the newly created spy in your controller.

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

Utilize ng-click in conjunction with an AngularJS directive

I'm encountering an issue while trying to create a directive and attaching ng-click with the template. Despite my efforts, when clicking on the template, it fails to log the statement from the scope.scrollElem function. The directive has been success ...

Step by step guide on accessing an object's property during a change event

I'm diving into my first angular app and I have to say, the framework is truly amazing. The goal is to create a price calculator that applies state tax after selecting a state. Here's what I have so far in my JavaScript: function testApp($scope) ...

Obtain specific styling for an element within an Angular directive

I have a question about displaying styles on an angular element. Is it possible to do so? <div ng-repeat="x in ['blue', 'green']" class="{{x}}"> <h3 insert-style>{{theStyle['background-color']}}</h3> ...

The controller is not receiving the output from the factory function

When my controller receives {"$$state": {"status" :0 } } from the factory instead of the expected value, how can I extract the correct value from the factory? Below is my code in controller.js: .controller('omnipayLoginCtrl', ['$scope&apos ...

Submitting a File Using AngularJS and PHP

Attempting to upload a file utilizing Angular JS and PHP through a formdata object. Wanting to utilize key1 (data) value as JSON to transmit filename and user info to the php script Opting for key2 (uploadFile), value being the file currently being uploa ...

Trouble with importing css in Angular webpack due to ui-bootstrap integration

Currently, I am developing an Angular application with Webpack and was looking to incorporate Bootstrap for styling purposes. To achieve this, I first installed 'ui-bootstrap' using npm install angular-ui-bootstrap --save-dev. After installation ...

Introducing the First Angular Factory

It's high time for me to finally inject my first angular Factory . . . Here is the code I have: .factory('Debts', function($q, $scope){ return MA; }) .controller('Admin', function ($scope, Debts) { $scope.Debts = Deb ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Encountered a timeout error of 2000ms while running tests on an asynchronous function within a service

Here is the service I am working with: class MyService { myFunction(param){ return Observable.create(obs => { callsDBfunc(param, (err, res) => { if(err) obs.error(err); ...

Encountering issues with Gzip compression in my Spring Boot 1.5.10.RELEASE project

I am currently running on Spring Boot version 1.5.10.RELEASE, but I'm facing issues with Gzip compression not working correctly. When accessing http://localhost:9000, it redirects to http://localhost:8080/api/.. My AngularJS and REST API are on dif ...

The Angulajrjs popup timepicker is not located within the input row

Currently, I am working on creating a popup timepicker within a modal. My main goal is to have the button inside the input field rather than after it. Does anyone know how I can achieve this? Thank you. If you need more context, you can check out my plun ...

Is the form data in AngularJS not submitting correctly?

Why is my HTML form data not being submitted using POST method? HTML View Page:- <div class="col-sm-12"> <div class="card-box"> <form class="form-inline" name="addstock" ng-submit="saveStockPurchaseInvoice()"> <h ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Angular routing based on login status

Currently, I am utilizing active directory windows authentication to verify if a user is logged in. The client-side code is written in Angular while the server-side code is in C#. How can I implement Angular to verify user authorization for accessing a pa ...

Testing the use of rxjs fromEvent in Angular while mocking subscriptions

In the Angular component, I have an array of objects representing companies that are provided via @Input(). Upon loading this data, which is obtained from an HTTP request, I assign it to another variable called filteredList, which is used in an *ngFor dire ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

Is ngwebdriver compatible with Appium for testing iOS applications?

Our team is currently working on a Cordova angular mobile app and looking to implement automation testing. Since we are not well-versed in javascript, we prefer not to use the protractor tool. Is it possible to utilize ngWebDriver with appium and seleniu ...

What is the method to verify that an Action was sent from one Action to another in NGXS?

I've been utilizing NGXS extensively throughout an application, but there are certain tasks that I still struggle to accomplish in a satisfactory manner. The documentation and other questions on this topic haven't provided the answers I seek. One ...

Oops! Looks like we encountered a fatal error while running the unit tests. Unfortunately, the unit

After setting up the project environment and successfully installing grunt, I attempted to run grunt in the terminal which resulted in the following output: https://i.stack.imgur.com/4xnll.png I proceeded to follow the steps. Running grunt build --env ...

Issues with ng-repeat causing the Angular Editable table to malfunction

<table class="table table-bordered"> <tbody> <tr ng-repeat="playerOrTeam in template.editableTable track by $index"> <td style="text-align: center;" ng-repeat="playerOrTeamCat in playerOrTeam track by $index"> ...