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

What is the best way to implement custom serialization for Date types in JSON.stringify()?

class MyClass { myString: string; myDate: Date; } function foo() { const myClassArray: MyClass[] = .... return JSON.stringify(myClassArray); // or expressApp.status(200).json(myClassArray); } foo will generate a JSON string with the date format o ...

Sharing an object's attributes as props in Vuejs

Greetings everyone, I am facing some confusion. I am working with two components (child and parent component) where I pass the properties of an object as props <child :child-data="abc" ></child> Vue.componen ...

Lazy loading a React grid gallery as you scroll

Currently, I am utilizing React grid gallery to showcase images from this repository: https://github.com/benhowell/react-grid-gallery. However, I am encountering an issue with lazy loading when the user scrolls on the page. <Gallery images={this ...

I attempted to activate the hover effect on a DOM element using JavaScript, but was unsuccessful. It appears that achieving this is not possible. However, I am curious as to how Chrome is able to

I attempted to activate the hover state of a DOM element using JavaScript, but had no success. It appears that this task is not achievable in the way I initially approached it. I have heard that creating a class with a hover function and then adding or ...

Attempting to streamline the process of verifying the truthfulness of an object key and subsequently adding it to a different

In the process of creating a form to interact with a remote API, I aim to construct a GET request query string depending on which checkboxes the user chooses. Initially, I considered using a series of if/else statements to check whether the model object k ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Unveiling Parameters from a Function Transferred as an Argument to Another Function in JavaScript

I'm just getting started with JavaScript and I've encountered a small program where a function takes another function as an argument. My goal is to figure out how to extract or access the arguments of that passed in function. Here's a specif ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Attempting to retrieve an object's attribute

Hey! I have a question regarding the screenshot in this link: I'm trying to access the user object with the property team. So far, I've attempted using data.Object, but it returns an undefined output. I also tried using data.user but that resul ...

Trying to convert <image> from canvas to png or base64 is not functioning properly

Currently, I am dealing with a grid div element that contains various HTML tags such as <div>, <p>, and <img>. I need to convert this grid to canvas and then encode it to base64 for saving on the server using PHP. Can someone assist me i ...

How can I activate the .opened() function in an angular-ui modal?

Currently, I am exploring methods to trigger the .opened() function for my modal. My goal is to have this function triggered after all the data has been loaded into the modal. I understand that by default, the opened() function is triggered when the modal ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

Strategies for handling missing and unused keys in i18n language files

In the realm of Rails/Angular webapps, we have a unique way of translating our app. We utilize both Ruby Globalize i18n with yml language files and angular-translate with json language files. However, managing these language files can become quite arduous. ...

I'm wondering if there exists a method to arrange a multi-array in javascript, say with column 1 arranged in ascending order and column 2 arranged in descending order?

Here is an example of a randomly sorted multi-array: let arr = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]]; The goal is to sort it in the following order: arr = [[1, "O" ...

The window fails to load properly after building, but functions perfectly while in development server mode

My application is not displaying a window after it's built, but it works perfectly fine when I execute npm run serve Even though there is a process running in the task manager, the same issue persists if I try using the installer. I'm not receiv ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

What is the process of generating a row in AngularJS?

I am struggling to create a row as shown in the image. Currently, my circle is not positioned on the right side and my "P" element is not receiving the background color. Here is the code snippet: http://plnkr.co/edit/qIz2rFgW8n3J92evCRTd?p=preview Is it p ...

Ways to implement StackNavigator along with Redux?

Is there anyone who can assist me in integrating StackNavigator and Redux? It seems straightforward, but I'm encountering issues. index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import { Provi ...