"Exploring the world of Angular JS through testing controllers with jasmine

I'm currently facing an issue with my test in the controllersSpec.coffee Angular App code:

describe 'Controllers', ->
  beforeEach ->
    angular.module 'app'
  describe 'MainCtrl', ->
    beforeEach inject ($controller, $rootScope) ->
      scope = $rootScope.$new()
      ctrl = $controller 'MainCtrl', $scope: scope
    it 'should be true', ->
      expect(true).toEqual(true)

This is the content of my SpecRunner.html file used for testing:

<html lang="eu">
  <head>
    <title>Angular Test Runner</title>
    <script src="../js/libs/jquery.js"></script>
    <script src="lib/jasmine.js"></script>
    <script src="lib/jasmine-html.js"></script>
    <script src="../js/libs/underscore.js"></script>
    <script src="../js/libs/angular.js"></script>
    <script src="lib/angular/angular-mocks.js"></script>
    <script src="lib/angular/angular-scenario.js" ng-autotest></script>
    <script src="../js/controllers.js"></script>
    <script src="controllersSpec.js"></script>
    <script type="text/javascript">
    (function() {
    var jasmineEnv = jasmine.getEnv();
    jasmineEnv.updateInterval = 1000;
        var htmlReporter = new jasmine.HtmlReporter();
    jasmineEnv.addReporter(htmlReporter);
    jasmineEnv.specFilter = function(spec) {
      return htmlReporter.specFilter(spec);
        };
    var currentWindowOnload = window.onload;
    window.onload = function() {
      if (currentWindowOnload) {
        currentWindowOnload();
          }
          execJasmine();
        };
        function execJasmine() {
       jasmineEnv.execute();
    }
    })();
    </script>
    </head>
    <body>
    </body>
</html>

However, I am encountering an error related to '$modules' in angular-mock:

TypeError: Cannot read property '$modules' of null
    at Object.workFn (http://localhost/lolobot/test/lib/angular/angular-mocks.js:1745:25)
    at Object.<anonymous> (http://localhost/lolobot/test/lib/angular/angular-scenario.js:24673:54)
    at Array.forEach (native)
    at Object.forEach (http://localhost/lolobot/test/lib/angular/angular-scenario.js:9538:11)

If anyone has insight on how to resolve this issue, I would greatly appreciate your help as this is my first experience testing an Angular app.

Answer №1

It seems like including more Angular packages might be necessary in your setup. Personally, I've added the entire suite to my runner even though I may not actually need all of them. Removing some has caused failures for me in the past. Currently, these are the ones I have included:

angular.js
angular-bootstrap.js
angular-cookies.js
angular-loader.js
angular-mocks.js
angular-resource.js
angular-sanitize.js

Furthermore, when writing tests, make sure to initialize

controller = null
scope = null

at the beginning of your describe block. This way, your controller and scope won't be treated as local variables within the inject function.

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

Triggering multiple onClick events in React / Material-UI when used within a data.map() loop

My English may not be perfect. {data.sort(getSorting(order, orderBy)) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map(n => { {/*........*/} <Button onClick={this.handleLsClick}> Open Menu < ...

Can $scope be considered as a dependency in this scenario?

My perspective is this: When you include a controller parameter called $scope, AngularJS recognizes the $scope parameter and generates the $scope object, injecting it into our controller where the $scope parameter was placed. Is injecting that object con ...

Verifying the functionality of a m3u8 URL with Javascript

I have been using the following code to check if an m3u8 URL is broken or not. I tried with two different URLs, one that is live and one that is offline. However, my javascript function does not alert me whether the file exists or not. There are no errors ...

Identical HTML elements appearing across multiple DOM pages

My question might seem silly, but I'm facing an issue. I have several HTML pages such as index.html and rooms.html, along with a main.js file containing scripts for all of these pages. The problem arises because I have variables like const HTMLelemen ...

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Navigating between divs with a 100% height using up and down movements

I am working on a website that is structured into different sections using divs with shared classes but unique IDs. Each div is set to take up 100% of the viewport height. To navigate between these sections, I want to provide Up/Down arrow buttons for user ...

Filtering JSON objects in Vue when the API is only returning a limited number of items

Currently, I am retrieving a JSON Object from an API with a limit of 200. The process involves fetching the initial 200 like this: https://testapi.com/posts.json In our application, we have implemented pagination with 10 posts per page. When we reach pag ...

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Exploring ng-repeat with a nested array structure within a JSON data format

I am encountering difficulties accessing specific values stored in a JSON object using the ng-repeat directive. The JSON is properly formatted (validated with a JSON checker) and is fetched using the $http service. Unfortunately, I am unable to modify the ...

Error: Unable to extract the 'id' property from 'this.props.Name' because it is undefined in ReactJS

Can you please assist me in resolving this issue? Error: Cannot destructure property 'id' of 'this.props.Name' as it is undefined. src/component/Detail.js file import React, { Component } from 'react'; import { Character } f ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Avoid displaying the image when encountering a 404 error, but sometimes a broken image may still appear momentarily

Here is the code snippet I'm currently using: <img ng-show="json.user.picture" ng-src="{{json.user.picture}}" ng-error="json.user.picture = false"> When accessing an image from an external website without permission, a 404 error code is return ...

What is the process for determining the files array in the nx dep-graph?

With each new release of NX v16.1.4, the file node_modules/.cache/nx/nxdeps.json is created. The structure of this file differs from the one generated by nx graph. In previous versions up to 16.1., the file contained an array named nodes.<app/lib>.d ...

Custom AngularJS directive that permits only alphabetic characters, including uppercase letters and the ability to input spaces

I'm currently working on an AngularJS directive that is meant to only allow alphabetical characters, however, I've encountered an issue where it disables caps lock and space functionality. While the main goal is to prevent special characters and ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

What is the best way to specify when form inputs are required in AngularJS?

Imagine developing a contact management application (for demonstration purposes) utilizing AngularJS. We have crafted a contact form that includes fields for email and phone number. We aim to make one of the two mandatory, but not both: The email field sh ...

Can we add to the input field that is currently in focus?

Recently, I've been working on a bookmarklet project. My goal is to append an element to the currently focused input field. For instance, if a user clicks on a textarea and then activates my bookmarklet, I want to insert the text "Hello" into that sp ...

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...