What methods can be used to perform unit testing on a controller within an AngularJS Directive?

My command is:

window.map.directive('dosingFrequencies', [
  function() {
    return {
      restrict: 'E',
      scope: true,
      templateUrl: '/views/directives/dosingFrequencies.html',
      controller: function($scope, util) {
console.log('starting now!');

        angular.extend($scope, {
          model: createModel(),

          addFrequency: function(med) {
            med.frequencies.push(createFreqModel());
          },

          removeFrequency: function(med, index) {
            med.frequencies.splice(index, 1);
          },

          showTimeChecked: function(freq) {
            if (freq.showTime) {
              freq.prn = false;
              freq.quantity = '';
              freq.quantityWhole = '';
              freq.quantityFrac = '';
              resetTimeToFirstLast(freq, this.model.facilityTimezone)
            }
            if (!freq.showTime) {
              for (var z = 0; z < freq.doses.length; z++) {
                freq.doses[z].quantity = '';
                freq.doses[z].quantityWhole = '';
                freq.doses[z].quantityFrac = '';
              }
              resetTimeToAllday(freq, this.model.facilityTimezone);
            }
          },

          updateDosingForm: function(med) {
            med.template.dosingForm = doseUnitChoices[med.med.dosingUnit] || ['', ''];
          }
        });

      }
    };
  }
]);

My assessment is:

fdescribe('MedPickerController', function() {
    var $scope;

    beforeEach(function() {
      module('mapApp');

      var html = '<dosing-frequencies></dosing-frequencies>';

      inject(function($compile, $injector) {
        var $controller, $rootScope, $httpBackend;
        $rootScope = $injector.get('$rootScope');
        $httpBackend = $injector.get('$httpBackend');

        $httpBackend.whenGET('/views/directives/dosingFrequencies.html').respond(200);

        $scope = $rootScope.$new();

        var elem = angular.element(html);
        var compiled = $compile(elem)($scope);

        var controller = elem.controller();

        $scope.$digest();

      });
    });

    it('should extend the scope', function() {
        expect($scope.model).not.toBeUndefined();
    });
});

However, my test does not pass. The console.log in my controller also does not run. What mistake am I making?

Answer №1

Create a dedicated controller instead of using an anonymous function for better organization.

Instead of:

{
  // ... some directive options
  controller: function() {
    // Your controller's logic
  }
}

Try something like this.

{
// ... some directive options
  controller: "MedPickerController"
}

Define your controller separately, just like you would with any other controller. You can even include them in the same file without any issues.

At this point, you'll simply be writing tests for the controller itself, regardless of it being used in a directive.

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 it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

Exploring the usage of multidimensional arrays in React components

How can I extract data such as teamId from the "teams" array using datas.map() method in a multidimensional array? Any tips or help would be appreciated. Is there another way to map out this data? { "gameId": 3226262256, "platformId": "NA1", " ...

Issue: Unable to locate 'child_process' module in Angular-cli

After creating a new application with angular-cli and adding components, I encountered an error when trying to run/build the application without any test cases included. The error message received was quite lengthy: ERROR in ./node_modules/selenium-webdri ...

Accessing HTML elements that are created dynamically in AngularJS

I am facing an issue where I cannot access a function within a newly created DOM element. Despite my best efforts, I can't seem to figure out what is causing this problem. $scope.createCustomHTMLContent = function(img, evtTime, cmname, evt, cust, ser ...

Keep fancybox items in their designated spot

When the window is opened at full size, everything looks fine. However, when you resize the window horizontally, the thumbnails shift and disappear. I want them to remain fixed in their position like the large pop-up image so that users can still see them ...

execute numerous Jssor Caption instances simultaneously

I have a Jssor slider and I want to create an animation for the first slide. My goal is to make two images come from the sides and merge in the center. I tried using a div for each image with a caption, and it works well. However, the second image starts ...

What is the best location to create the content for a sidebar?

Currently in the process of building my new website using express. The layout consists of various "sections" such as a blog, project information, and more. I want to have a unique sidebar next to the main content for each section. For instance, in the "blo ...

How can I use absolute positioning and scrolling with an Iframe?

One of the key elements of this website is the implementation of iframes, with only one displayed at a time. However, my current issue revolves around the inability to scroll within these iframes due to their absolute positioning. I have attempted variou ...

Placing elements from an array into a customized output

Currently, I am dealing with a unique output: dAmn_Raw('send chat:Sandbox\n\nmsg main\n\nthismessage'); In my code, there exists a variable: myvariable that stores a random value selected from an array I formulated. The cha ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...

Registration process in Node Express application encounters persistent loading when accessed through Postman

I've been working on a signup model for user accounts in Node.js, but when testing it in Postman, I encountered an issue where there was no response or failure. This left me stuck and I received the following error message in my terminal: Unhandled ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Switching the active className in React and Next.js based on selection status

My goal is to dynamically change the className of each Card component when clicked on. When one Card is selected, the others should revert back to their default className. This is my UserBookingData component: const UserBookingData = ({ bookings }: any) = ...

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

Is there a way for me to adjust the image dimensions so that it doesn't surpass the width of its parent container?

When working with images, it can be tricky to set the original width while also ensuring it fits within a parent container. For example, if the parent container has a width of 1000px, you may want the image to have a max-width of 100%, but not exceed 1000p ...

Searching for a jQuery plugin that can dynamically rearrange tables while automatically updating their corresponding IDs

Is there a way in jQuery to dynamically move tables around on a webpage? Currently, I have implemented a button that clones a hidden table when needed and another button to delete unwanted tables. Now, I am looking to incorporate a feature that allows the ...

Preventing a Click Event on Child Element from Triggering the Parent's Click Event in jQuery

Can you help me figure out how to prevent a button from executing the onclick function of its parent div in this example? <div onclick="$('#extra-info').slideToggle();" class="card card-body item"> <div class="ro ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

ESLint flags a misuse of promises in my code that I believe is acceptable

This symbol table implementation includes a method that needs some adjustments: public getAllSymbols(type?: typeof Symbol, localOnly = false): Promise<Set<Symbol>> { const promise = super.getAllSymbols(type ?? Symbol, localOnly); ...

Is there a way to arrange an HTML list in this specific manner using CSS or JavaScript?

I need to arrange a list of items in columns with 5 rows each, as shown in the attached image. This list is generated dynamically using an SQL query with a loop on the li tag. I am looking for a solution to order the list in this way using javascript or ...