AngularJS testing typically involves the use of the inject module injection process

Currently, I am working on testing a service called documentViewer, which relies on another service named authService.

  angular
    .module('someModule')
    .service('documentViewer', DocumentViewer);

  /* @ngInject */
  function DocumentViewer($q, authService) {
    // ...

    this.view = function(doc) {
      //...
    }
  }

This is the structure of my test at the moment:

it('test', inject(function($q) {
  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };

  var auth = {
    refreshProfileData: function() {
      return $q.resolve(0);
    },
  };

  var viewer = createViewer(auth);
}));

function createViewer(auth) {
  var viewer;

  module({
    authService: auth
  });
  inject(function(documentViewer) {
    viewer = documentViewer;
  });

  return viewer;
}

The issue arises when I attempt to use inject to obtain a $q, then utilize it to generate my mocks, register those mocks with module, and finally invoke inject again to fetch the unit I am testing.

As a result, I encounter the following error message:

Error: Injector already created, can not register a module! in bower_components/angular-mocks/angular-mocks.js (line 2278)

I have come across various responses stating that calling module after inject is not allowed, but none of them provide an alternative solution for a scenario like the one I am facing here.

So, what would be the correct approach in this situation?

PS: I prefer not to use beforeEach, as I want each test to stand alone.

Answer №1

module is utilized to specify the modules that will be loaded with inject and must not be called after inject, creating a chicken-egg dilemma.

The object acknowledged by module is employed to define simulated services using $provide.value:

If an object literal is provided, each key-value pair will be registered on the module via $provide.value, with the key representing the string name (or token) associated with the value on the injector.

Only one function like createViewer that calls both module and inject is allowed. If following this pattern of self-contained testing is considered unfavorable, there might not be a solution to alter it. Angular testing is most effective when conventional practices are upheld, including the use of beforeEach and local variables.

To remove the dependency on $q, a simulated service can be turned into a factory.

it('test', function () {
  var authFactory = function ($q) {
    return {
      refreshProfileData: function() {
        return $q.resolve(0);
      },
    };
  };

  // defined mocks first
  module(function ($provide) {
    $provide.factory('authService': authFactory);
  });

  var viewer;
  inject(function(documentViewer) {
    viewer = documentViewer;
  });
  // no more module(...) calls allowed beyond this point

  var $q;
  inject(function(_$q_) {
    $q = _$q_;
  });

  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };
});

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

The requested command is not being recognized

Just starting out with these commands as I dive into learning Angular.js through a book. npm install –g grunt-cli npm install –g bower npm install –g generator-angular After successfully running all the commands, I attempted to create a folder in C ...

The reactivity of Vuex and Vue does not work as expected when a dictionary is used as a

What is the best approach to make a dictionary reactive as one of my store variables? Unlike an array, dictionaries are not reactive by default. Here's a minimal example I've created: Check out this example on CodeSandbox ...

Moving from the center to the bottom-right with a CSS transition

I have a specific requirement where I need the container to cover the entire page and shrink when clicked, with an animation. Currently, I am using CSS transition to animate the container shrinking towards the top: The container shrinks slowly to the sp ...

Is there a way to monitor and trigger a function in jQuery when a loaded PHP file is modified?

I am currently working on a dynamic dashboard that automatically updates every few seconds to display new information fetched from a PHP file. My goal is to trigger an alert only when there is a change in the data itself, rather than just a refresh. In ord ...

The jQuery date picker is showing an error with the function daySettings[2].replace, indicating that

Encountering a problem with the jQuery version I am using: <script src="js/Common/jquery-2.1.1.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> The code I have writte ...

Tips for adding CSS attributes to a <style> tag in Internet Explorer

My current issue involves an ajax web application that loads all parts on a single page, specifically index.html. The inner parts being loaded in index.html have exceeded 32 pages (html, js, css). Now I am facing difficulties with the CSS files that need ...

Exploring the implementation of query parameters in Nest.js

I am currently a freshman in the world of Nest.js. Below is an excerpt from my code: @Get('findByFilter/:params') async findByFilter(@Query() query): Promise<Article[]> { } I have utilized Postman to test this specific router. ht ...

Expanding the size of a Three.js geometry in one direction

I've been experimenting with scaling geometries on the y-axis, but I've run into an issue where my cube scales both up and down. I found that using mesh.transformY to animate the cube up by half of the scaling value can create the illusion of the ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

The onCreated listener function in the jBox Modal dialog is experiencing issues and not functioning properly after the first use

I am using jBox from the URL: . Every time I click on a link, a modal is created. The first time the modal is created, listeners for the buttons on that modal are properly added in the "onCreated" attribute and work when clicked. However, from the second ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

Issue with toggling JS checkboxes selection

Seeking assistance in expanding my knowledge of Javascript. I have a form with checkboxes and a JavaScript function that allows toggling between selecting and deselecting all the boxes. Everything is functioning as intended so far. The challenge arises f ...

What strategies would you use to put in place conditional imports in a way that is reminiscent of ReactNative

Is there a way to implement conditional imports in other projects similar to how React Native imports Android or iOS specific classes using *.android.js and *.ios.js? If I wanted to have different classes for development and production purposes, could I u ...

Tips for reducing the amount of repetitive code in your reducers when working with redux and a plain old JavaScript object (

When it comes to writing reducers for Redux, I often encounter challenges. My struggle usually lies in wrapping a lot of my state manipulation in functions like .map and .slice. As the structure of my state object becomes more complex, the reducers become ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Angular: Variable `app` has not been defined

I am working on a simple MEAN stack app and it is almost up and running, but I encountered an uncaught reference error when it tries to redirect to the index page. The server seems to be running fine and the browser displays "Loading..." as expected on the ...

Modifying the class when ng-focus is triggered in AngularJS

Here is the HTML code that I am working with: <div class="icon fluid select" ng-init="focused = false"> <i ng-class="{'large svg guests icon':rooms==2, 'large svg guest icon':rooms==1,'active':focused==true}"> ...

Exploring the features of Vue.js with the code snippet 'ts 1109'

I need some assistance with my code as I seem to have one incorrect answer when using the if statement. The error code that I am encountering is ts1109 and I am not sure why VS Code is showing this. Thank you in advance for any help provided :) var calcu ...