Injecting AngularJS service into a karma-mocha test: Step-by-step guide

I have developed a Karma-Mocha test that involves injecting an AngularJS service.

Service Code:

(function() {
    'use strict';
    angular.module('portal').service(
            'AmountFormatService',
            function() {

                return {
                    format : function(amount) {

                        if (amount != null) {
                            var isNegative = false;
                            if (amount.substring(0, 1) == '('
                                || amount.substring(0, 1) == '-'
                                || amount.substring(1, 2) == '-'
                                || amount.substring(1, 2) == '(') {
                                isNegative = true;
                            }
                            amount = amount.replace(/[^0-9.]/g, '');
                            if (isNegative) {
                                amount = '-' + amount;
                            }
                        }
                        if (amount == '')
                            amount = null;
                        return amount;
                    }
                }
            }); 
    })();
    

Karma Test:

describe('AmountFormatService', function () {

    var amountFormatService;

    beforeEach(function(){
        angular.mock.module('portal', function(){
        });

        inject(function(_AmountFormatService_){
            amountFormatService = _AmountFormatService_;
        });

    });

    it('does something', function(){
        //Expect this to do something
        console.log(amountFormatService.format(23));
    });
    });
    

karma.conf.js (karma config file):

module.exports = function (config) {config.set({
    frameworks: ['mocha', 'chai'],

    files: [
        '../../../node_modules/angular/angular.js',
        '../../../node_modules/angular-mocks/angular-mocks.js',
        '../../main/webapp/app.js',
        '../../main/webapp/services/*.js',
        '../../test/testAmountFormatService2.specs.js',
        '../../main/webapp/services/AmountFormatService.js'
    ],

    // coverage reporter generates coverage
    reporters: ['progress', 'coverage'],

    preprocessors: {
        // source files for coverage
        '../../main/webapp/services/*.js': ['coverage']
    },

    coverageReporter: {
        dir : '../../../target/JSCodeCoverage/',
        reporters: [
                    { type: 'html', subdir: 'report-html' },
                    { type: 'cobertura', subdir: '.', file: 'cobertura.txt' }
                ]
    },

    browsers: ['Firefox', 'IE'],

    autoWatch: true,

    plugins: [
        'karma-firefox-launcher',
        'karma-ie-launcher',
        'karma-junit-reporter',
        'karma-mocha',
        'karma-chai',
        'karma-coverage'
    ]
    })
    }
    

Encountering an error when running the test:

Error: [$injector:unpr] Unknown provider: AmountFormatServiceProvider <- AmountFormatService
    http://errors.angularjs.org/1.6.4/$injector/unpr?p0=AmountFormatServiceProvider%20%3C-%20AmountFormatService
    // AngularJS error details follow...
    

If anyone can provide insight into the issue, it would be greatly appreciated.

Answer №1

Make sure to import the portal module instead of faking it:

- angular.mock.module('portal', function(){
- });
+ beforeEach(module('portal'));

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

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

Vue application encountering issues with the functionality of the split method in Javascript

Hey there! I am just starting out with JS and Vue. Currently, I have a Vue application that pulls date information from an open API. The tricky part is that the API response includes both the date and time in one string (for example: 2019-10-15T09:17:11.80 ...

Struggling with implementing React routing in version 4.0

Struggling to route multiple pages using BrowserRouter in Reactv4. Many online guides are outdated and not working with the latest version. Here is my setup: Index.js: import React from 'react'; import ReactDOM from 'react-dom'; impo ...

Ensure that the first option in the Woocommerce 2 Variable Product Dropdown List always displays all available choices

I am currently working on a variable WooCommerce product that includes 2 drop-down select fields. The first field is for selecting the Type of Product (framed or unframed artwork) and the second field is for choosing the Size of Artwork. With the help of ...

JavaScript: Understanding the concept of closure variables

I am currently working on an HTML/JavaScript program that involves running two counters. The issue I am facing is with the reset counter functionality. The 'initCounter' method initializes two counters with a given initial value. Pressing the &a ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Why is it that I am not receiving JSON data in my Angular application?

I am currently working on a class within a webapi public class ResponseObject { public int Success { get; set; } public string Message { get; set; } public object Data { get; set; } } Within my ASP.NetCore, I have the following method: publi ...

Tips for refreshing $('select') with .material_select() once the $http request is finished

Currently, I am utilizing Angular and Materializecss for my project. I am facing an issue where I want to update material_select() after the completion of $http request, but I have been unable to find a suitable solution so far. Here is what I have attemp ...

What causes a 400 Bad Request error when attempting to send data using jQuery Ajax within the Spring framework

I am facing an issue with submitting JSON data through jQuery AJAX. I have searched for similar problems online, but none of the solutions seem to be working for me. $.ajax({ type : "POST", contentType : "applic ...

Material UI grid items overlapping issueIn Material UI, the grid

Here is a snippet of code for your review: <div className="mx-md-4 my-5 mx-sm-0 mx-xs-0 flex-column align-items-center d-flex justify-content-center "> <Grid className='mt-3' container spacing={2}> ...

A Node.js function may not provide a response immediately due to a pending request

Here is a simple upload method using node.js and express.js: upload: function(req, res, next){ // Loop through each uploaded file async.each(req.files.upload, function(file, cb) { async.auto({ // Create new path and unique file ...

How can I target the first checkbox within a table row using jQuery?

I am seeking a way to determine if the first checkbox in a table row is selected, rather than checking all checkboxes within that particular row. Currently, I am using this code: var b = false; $j('#tb1 td input:checkbox').each(function(){ ...

Is there a way to collapse child elements in a hover sidebar using Vuetify?

My project includes a sidebar that opens when I hover over it with the mouse. Everything works fine, but within the sidebar, there is a collapse dropdown menu. When I open this menu and then move the mouse away from the sidebar and back again, the collapse ...

Tips for displaying a loading message during an AJAX request?

My AJAX function is set up like this: function update_session(val) { var session_id_to_change=document.getElementById('select_path').value; $.ajax({ type: "GET", url: "/modify_path/", asy ...

Issues with LocalStrategy not executing in passport authentication

I am currently facing an issue with authenticating using Passport and LocalStrategy. It seems like the strategy is not being called and when I log the user object in passport.authenticate, it returns "false". Below is my client-side code: logIn = () =& ...

Angular 5 - Creating a dynamic function that generates a different dynamic function

One of my latest projects involved creating a versatile function that generates switch-case statements dynamically. export function generateReducer(initialState, reducerName: ReducerName, adapter: EntityAdapter<any>): (state, initialState) => ISt ...

Getting Javascript as a string using Selenium in Python

Is it possible to retrieve JavaScript code using Python Selenium? Specifically, I want the JS code as a string. function validateForm() { var x = document.forms["myForm"]["Password"].value; if (x.length >= 6) { } } ...

The dropdown in vue-multiselect automatically closes after the first selection is made, ensuring a smooth user experience. However,

I am experiencing an issue where the dropdown closes after the first selection, despite setting close-on-select="false". However, it works properly after the initial select. You can observe this behavior directly on the homepage at the following link: vue ...

Issue with Vue/Nuxt 3: Unable to modify properties of null when setting 'textContent'

I am currently facing an issue with a function that is designed to switch words every few seconds. The functionality itself is working fine, but I keep encountering the following error intermittently in the VSC console: TypeError: Cannot set properties o ...

Enhanced MUI TextField component with active cursor and focused state

When using the MUI TextField component as a single input form, I encountered an issue where the component loads with focus but no visible cursor to begin typing. To start typing, the user must click into the input field or press the tab key, which then act ...