Exploring the resolution of unit test for an Angular Bootstrap modal using the John Papa ViewModel style

A custom ModalService has been created to display two different types of dialogs, CancelDialog and ErrorDialog, based on the parameter passed to the service.

For example, the following code will show an ErrorDialog:

ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');

The unit test for the resolve function is failing. You can view the running Unit Test in this PLUNKER.

This functionality is defined in the file ModalDialogService.js. Here is a snippet of the code:

function openCancelModal(title, message, callback) {
  $uibModal.open({
    templateUrl: 'CancelDialog.html',
    controller: 'DialogController',
    controllerAs: 'vm',
    backdrop: 'static',
    size: 'md',
    resolve: {
      message: function() {
        return message;
      },
      title: function() {
        return title;
      },
      callback: function() {
        return callback;
      }
    }
  });
}

The corresponding test file is named ModalService.spec.js:

describe('ModalService', function() {

var $injector;
var $uibModal;

// Inject the module of your controller
beforeEach(module('validationApp', function($provide) {
  $uibModal = {
    open: jasmine.createSpy('open')
  };

  $provide.value('$uibModal', $uibModal);
}));

beforeEach(inject(function(_$injector_) {
  $injector = _$injector_;
}));

it('tests that openErrorModal is called', function() {
  var modalService = $injector.get('ModalService');
  modalService.openModal(null, null, "Error");

  expect($uibModal.open).toHaveBeenCalledWith(jasmine.objectContaining({
    controller: "DialogController",
    templateUrl: 'ErrorDialog.html',
    resolve: {
      message: function() {
        return message;
      },
      title: function() {
        return title;
      },
      callback: function() {
        return callback;
      }
    }
  }));
});


it('tests that openCancelModal is called', function() {
  var modalService = $injector.get('ModalService');
  modalService.openModal(null, null, "Cancel");

  expect($uibModal.open).toHaveBeenCalledWith(jasmine.objectContaining({
    controller: "DialogController",
    templateUrl: 'CancelDialog.html'
  }));
});

});

An error is occurring in the testing phase:

Expected spy open to have been called with [ <jasmine.objectContaining(Object({ controller: 'DialogController', templateUrl: 'ErrorDialog.html', resolve: Object({ message: Function, title: Function, callback: Function }) }))> ] but actual calls were [ Object({ templateUrl: 'ErrorDialog.html', controller: 'DialogController', controllerAs: 'vm', backdrop: 'static', size: 'md', resolve: Object({ message: Function, title: Function, callback: Function }) }) ].

If you need further assistance, you may find this ANSWER helpful in resolving the issue around covering unit tests for the resolve function using the vm style.

Answer №1

fdescribe('ModalService Test', function () {

    var $injector;
    var $uibModal;
    var testOptions;

    // load the necessary module for testing
    beforeEach(module('validationApp', function ($provide) {
        $uibModal = {
            open: jasmine.createSpy('open').and.callFake(function (options) {
                testOptions = options;
            })
        };

        $provide.value('$uibModal', $uibModal);
    }));

    beforeEach(inject(function (_$injector_) {
        $injector = _$injector_;
    }));

    it('verifies that resolve returns expected values', function () {
        var title = {};
        var message = {};
        var callback = {};

        var modalService = $injector.get('ModalService');
        modalService.openModal(title, message, "Error", callback);

        expect(testOptions.resolve.title()).toEqual(title);
        expect(testOptions.resolve.message()).toEqual(message);
        expect(testOptions.resolve.callback()).toEqual(callback);
    });

});

Check out the live demo on Plunker

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

Integrating Facebook login with Cordova using the cordovaOauth plugin

Encountering issues while setting up FB login for my cordova mobile app. A tutorial followed: http://www.codeproject.com/Tips/1031475/How-to-Integrate-Facebook-Login-into-a-Cordova-App#_comments <script src="js/angular.js"></script> <scrip ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...

The functionality of Everyauth seems to be malfunctioning in the latest version of Express

Currently, I am utilizing nodejs, express 4, and everyauth for social network authentication. I have encountered an issue where upon clicking Accept from Google and getting redirected back to my /, an error message appears: _http_outgoing.js:335 throw ne ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Issues with data not being successfully transferred between controllers in my service

Presenting my unique service: var CustomService = function () { var filters, charts, subscription; return { getFilters: function () { return this.filters; }, setFilters: function (value) { this.filt ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

Using a static function within a library's state function in NextJS is throwing an error: "not a function"

Inside a library, there's a special class known as MyClass. This class contains a static method named setData. The contents of the MyClass.js file are shown below: class MyClass { static DATA = ''; static setData(data) { MyClass ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

Obtaining the following class name from elements

I am struggling with extracting classes from a block of HTML code: <div class="container"> <div class="item first">...</div> <div class="item second">...</div> <div class="item third">...</div> <div cla ...

Troubleshoot: Trouble with selecting the clicked item in AngularJS when using ng-repeat

Is there a way to only delete the selected item from my ng-repeat list instead of deleting all items at once? I can currently delete all items using ng-repeat, but I want to be able to delete just the clicked item. How can I achieve this? https://i.stack. ...

Sharing information between React components involves passing data as props. By sending data from

Brand new to React and still figuring things out. Here's the scenario: <div> <DropDown> </DropDown> <Panel> </Panel> </div> After selecting a value in the dropdown and storing it as currentL ...

Guide on how to append input field data to a table using jQuery

My current project involves working with a table, and I have encountered some challenges along the way. Typically, I have 4 input fields where I can input data that is then sent to the table in my view. However, if I exceed 4 values and need to add more, I ...

Implementing global parameters in ui-router

Currently, I am utilizing ui-router in AngularJS as shown below: .state ('browse.category', { url: "/:category", templateUrl: "views/browseCategory.html", controller: function($stateParams, $scope) { $scope.params = $st ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Techniques for utilizing ng-class to merge class attributes

I'm new to Angular and I want to combine classes using ng-class. Specifically, I'd like to use the save class along with the firstClass class if something = First. I've been doing some research on how to implement this with ng-class but I ha ...

The AJAX request is not triggered before the postback when using a LinkButton in ASP

I am facing an issue with running an insert statement using a button in my application. Although it is functional, I have noticed that whenever I click the button, the Page_Load function runs before the ajax statement executes. How can I ensure that the a ...

The `.append()` function includes HTML content as plain text

I am using JavaScript to dynamically add HTML elements to my webpages. I have created a loop that iterates through all the projects, each containing multiple pictures. The first step involves generating the project title and adding it within a div element ...