When testing units, the scope method in an AngularJS directive fails to execute

I am facing an issue with my Mocha test:

'use strict';

///////////////////////////////////

describe('all admin page directives', function () {

  let scope, $compile, element, tmp;
  beforeEach(module('app'));
  beforeEach(module('templates'));

  afterEach(function () {
    scope.$destroy();
  });

  describe('category', function () {

    beforeEach(inject(function ($injector) {
      $compile = $injector.get('$compile');
      var $rootScope = $injector.get('$rootScope');
      scope = $rootScope.$new();
      scope.rightSidebarData = {};
      $compile('<create-category right-sidebar-data="rightSidebarData"></create-category>')(scope);
      return scope.$digest();
    }));

    it('should do something', function () {
       scope.updateModel();           //     <<<<<<  ERROR HERE
    });


  });

});

Looking at my directive:

/* globals angular */

angular.module('app').directive('createCategory',

  ['UserService', 'AssignmentService', 'NotificationService', 'USER', 'UserInfoService', 'AlertService', '$window',

    function (UserService, AssignmentService, NotificationService, USER, UserInfoService, AlertService, $window) {

      return {

        scope: {
          rightSidebarData: '=',
        },

        restrict: 'EA',
        templateUrl: "pages/admin/views/templates/category/create-category.html",

        link: function ($scope, el, attrs) {

          $scope.rightSidebarData.setOrReset = function () {
            $scope.setOrReset();
          };

        },

        controller: function ($scope, FUNCTIONAL_TEAM_ENUM, CATEGORY_ENUM, CategoryService) {

          const rsd = $scope.rsd = $scope.rightSidebarData;

          $scope.setOrReset = function () {...};

          $scope.updateModel = function () {...};

          $scope.saveModel = function () {...};

        },
      };
    }
  ]);

There is an error occurring:

TypeError: scope.updateModel is not a function

I need assistance in resolving this error in my test. Additionally, how do I determine whether to use $rootScope.$new() or pass the parent controller's scope?

Answer №1

To make it work, I needed to include an additional preprocessor in my karma configuration file:

preprocessors: {
  './public/pages/**/views/**/*.html':['ng-html2js'], // this
},

After adding that, the following code successfully executed:

'use strict';    
describe('all admin page directives', function () {

  let scope, el, tmp, isoScope;

  beforeEach(module('app'));
  beforeEach(module('ngMockE2E'));
  beforeEach(module('templates'));

  afterEach(function () {
    scope.$destroy();
  });

  describe('category', function () {

    beforeEach(inject(function ($injector) {
      const $compile = $injector.get('$compile');
      const $rootScope = $injector.get('$rootScope');
      const $templateCache = $injector.get('$templateCache');
      console.log('create category template =>', $templateCache.get('pages/admin/views/templates/category/create-category.html'));

      scope = $rootScope.$new();
      scope.rightSidebarData = {};
      scope.rightSidebarData.model = {};
      let element = angular.element(`<create-category right-sidebar-data="rightSidebarData"></create-category>`);
      el = $compile(element)(scope);
      $rootScope.$digest();
      scope.$digest();
      el.isolateScope().setOrReset();
    }));

    it('should do something', function () {
      el.isolateScope().updateModel();
    });

  });

});

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

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

"Discover the best way to sort through an array of complex objects with varying levels of nesting using a specified search

I have come across similar answers, but none of them go beyond two levels deep. Therefore, I believe this is not a duplicate problem. My task is to filter an array of objects where each object may contain nested objects of unknown depth. In my data structu ...

Customize the appearance of Woocommerce's blockUi feature with your

During an Ajax request, blockUI adds a style to the blocks of the checkout form and cart with "background: '#fff'". However, my entire website theme is black and I do not want the background color of the blocks to be white. Is there a way to remo ...

Issue with AjaxComplete function failing to work

Currently, I am tackling the Opera workaround for printing IFrames. As we are aware, the only method to print an IFrame is by opening it in a new window and then printing it. However, I am encountering an issue where a series of ajax calls are triggered wh ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

Having trouble with the authorization aspect of Next Auth. The error message reads: "NextAuth.js does not support the action api with HTTP GET method

Recently, I've been encountering a puzzling error with my Next.js app authentication. It seems that I am unable to authenticate with the provided credentials. After reviewing the documentation, everything appears to be correct on my end. Additionall ...

ReactJS Tutorial: Simple Guide to Updating Array State Data

const [rowData, setRowData] = useState([]); const old = {id: 'stud1', name: 'jake', room: '2'}; const newData = {name: 'jake', room: '3A'}; useEffect(() => { let ignore = false; ...

Error encountered in Firefox: THREE.js throws a TypeError because 'global' is undefined

After attempting to integrate three.js into my code as a standalone script without using webpack, browserify or requirejs, I encountered an issue. My setup involves loading an external Angular app and extending it, but now I need my own version of THREE.js ...

React-modal triggers the file-explorer upon exiting the dropzone

Within my project, I have implemented a button that triggers a modal to appear on mouse-over. This button is nested inside a dropzone element. https://i.sstatic.net/95dxy.png The issue arises when I exit the modal by clicking (not exiting with the escape ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

Steps for displaying an error message when incorrect credentials are entered during a login attempt

As I work on implementing a login feature, I am facing the challenge of displaying an error message when users enter incorrect login credentials. My development environment involves using the POST method within Next.js. Here is a snippet of my code: ...

A guide on smoothly navigating to the desired row in a gridview using Asp.net

Currently, I am developing a project using ASP.net and C# technology. In my application, I integrated a GridView that contains multiple rows. Within the grid, there is a text box and a search button available. The columns displayed in the grid are Id and ...

Cannot update VUEjs array following the splice operation

My array is only updating in the console and not in the DOM. I've already tried using :key but it's still not working. Here is my code: <div style="margin-top: 5px;" v-for="(file, index) in editedItem.file_name" ...

Use CSS and JavaScript to create a visually appealing and interactive tree structure. Give the tree a dynamic design

I have been experimenting with CSS and JavaScript to create a dynamic graph based on a data table. You can view the graph that I need to replicate using CSS and JavaScript in this PDF. The example provided below showcases what I am attempting to achieve, a ...

Is it possible to customize the notification message displayed after clicking the save button in a listview within ng-admin?

While working on the listview/creation view, I am attempting to incorporate a custom notification message instead of the default one (please see the screenshot) that appears when the user clicks the save button. Is there a way for me to include a custom n ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

Response from the server to multiple asynchronous XMLHttpRequests

I'm in the process of creating a Web Application that involves making multiple simultaneous XHR calls using Ajax instead of native Javascript. $.ajax({ type: 'POST', url: 'Services/Service.asmx/MyFunction', contentTyp ...

Elegant bespoke input box

I am looking to create a customized input text feature similar to StackOverflow's tag editor, but with some minor differences. The goal is for the input field to function like a regular text input until a word is enclosed in curly brackets. Once enclo ...