Having trouble executing Angular jasmine test using grunt karma?

I've been through the process of installing and reinstalling grunt, karma, and jasmine multiple times, but I'm still encountering the issue described below. When I run the test in Jasmine on its own, everything works perfectly fine. It doesn't appear to be a problem with the file path. However, when I use the grunt karma command, I encounter the following error:

This is what my Gruntfile.js looks like:

module.exports = function(grunt) {

  grunt.initConfig({

        karma: {
          unit: {
            configFile: 'c:/tools/karma.conf.js',
            autoWatch: true
          }
        }


      });

    grunt.loadNpmTasks('grunt-karma');

};

Here's my karma.conf.js file:

module.exports = function(config) {
  config.set({

    basePath: 'c:/tools/public/',    
    frameworks: ['jasmine'],
    files: [
        'libs/angular/angular.min.js',
        'libs/angular/angular-mocks.js',
        'test/cookbookspec.js'
    ],
    exclude: [
    ],
    preprocessors: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: true,
    concurrency: Infinity
  })
}

And here's the error message that keeps popping up:

C:\tools\npm>grunt karma

Running "karma:unit" (karma) task
01 01 2017 13:17:52.333:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
01 01 2017 13:17:52.333:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
01 01 2017 13:17:55.223:ERROR [PhantomJS]: Error: [$injector:modulerr]
...
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.

UPDATE

After switching to the non-minified AngularJS version, the error message has changed slightly:

C:\tools\npm>grunt karma
Running "karma:unit" (karma) task
01 01 2017 13:39:53.734:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
01 01 2017 13:39:53.734:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
01 01 2017 13:39:55.283:ERROR [PhantomJS]: Error: undefined is not a constructor
...
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.

The controller being tested:

angular.module('cookbook', [])
.controller('MainCtrl', function($scope) {
    $scope.sum = function () {
        $scope.result = $scope.x + $scope.y;
    }
});

And here's the corresponding Jasmine test:

describe('cookbook level 1', function () {

    beforeEach(angular.mock.module('cookbook'));

    var $controller;

    beforeEach(angular.mock.inject(function(_$controller_){
      $controller = _$controller_;
    }));

    describe('cookbook level 2', function () {
        it('should assign the correct rapper to scope', function () {
            var $scope = {};
            var controller = $controller('MainCtrl', { 
                $scope: $scope
            });
            $scope.x = 1;
            $scope.y = 2;
            $scope.sum();
            expect($scope.result).toBe(1+2);
        }); 
    });

Answer №1

To configure your karma.conf.js file, specify the files containing dependencies (e.g. angular.js), test scripts (in the test directory), and controllers being tested (located in the src directory):

files: [
        'libs/angular/angular.min.js',
        'libs/angular/angular-mocks.js',
        'src/cookbook.js'
        'test/cookbookSpec.js'
    ],

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

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

What is the best way to refresh the login page after successfully logging out using AngularJS?

Once a user signs out in my project, they are redirected to the 'login' state. However, if they try to log in again without refreshing the page, the login does not happen. It only works once the page is refreshed. Can someone please assist me wit ...

Dynamic array of objects in Angular using ng-repeat

When given a JSON array of objects, how can one dynamically display it using ng-repeat? The key error is static and always remains the same. Only the values of error change. For example, if the password field has an error, then the key will be password in ...

Revamp the md-select Container

Hello there! I'm looking for a stylish way to revamp the design of the md-select Window. Specifically, I aim to customize the background and hover effects. Despite my attempts to modify the .md-select-menu-container in CSS, it proved unsuccessful. I ...

Comparing Angular 2 Components and AngularJS Directives: What Sets

Are there any parallels or distinctions between an angular2 component and an AngularJS directive? It seems that these two share similar functionalities in the angular2 component and AngularJS directive. Additionally, angular2 also incorporates a directive ...

Issue: Unidentified source / Utilizing controller within factory

Is there a way to access AuthenticationCtrl in this code snippet? Snippet: app.factory( 'AuthenticationInterceptor', function( $q, $injector ) { return { response: function (response) { // Skip the success. ...

Creating a spy object in Jasmine for the forEach method of router.events

I have been attempting to create a test case for a component in an application and am having trouble with the constructor. Here is how it looks: constructor(private router: Router, public dialog: MatDialog, private tlsApiServi ...

The update function now saves only the name property in the database, while the url property is stored as undefined

I utilized nodejs, mongoose, and angular to create a RestAPI with mean stack, focusing on updating provider records in my database. Below is the implementation of the put method: Object {_id: "553d27a24c47696420c6ee39", name: "nn", url: undefined, __v: 0, ...

The Angular function resolved the promise before the HTTP API request finished executing

I am a beginner in AngularJs and I'm facing an issue with a validate function that returns a promise. This function makes an internal http get api call to receive a response in the form of a promise. The problem arises because the validation code need ...

Is there a way in AngularJS to trigger an event at a designated time?

I recently developed a webpage using AngularJS. I am looking to trigger certain actions on my webpage within a specified timeframe. For instance, If it is 2016-01-07 11:00:00, I want ng-show to execute some action. I am utilizing the Angular-timer for ...

The function has been called but it did not return a

It seems that there is confusion surrounding the .toHaveBeenCalled() Matcher in Jasmine. While it should return a Promise that resolves when the function has been called, some users are experiencing it returning undefined instead. For example: it('sh ...

Personalized directive for HTTP validation, display dialog box upon detection of incomplete match

Looking to validate input against a server-side REST API and provide options for selection if invalid while typing. Already implemented in jQuery, now looking to implement in AngularJS. Would it be better as a custom directive or functions in the controll ...

Utilizing Enum Types in Angular Templates

I have a set of server-side enums that I need to send to an Angular application. My goal is to access these enums in the following manner: <select ng-options="type.name as type.value for type in Enums.TYPES" /> I've attempted various methods ...

AngularJS: Utilizing angular-filter for grouping by two columns

I may come across as a bit confusing, so please allow me to clarify. Note: An operational piece of code (POC) has been included with this post. I have an array of objects with 3 properties: name name team team_rank $scope.players = [ {name: & ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

What steps do I need to take in order to modify information within a table using Symfony?

Working on my Symfony project, I frequently need to display various views in table format. I wish I could easily update the data by clicking on table cells, entering new information, and saving it dynamically. After exploring jqGrid, DataTable with jEdit ...

The sqlite database is throwing an error stating that it cannot read the property 'firstname' of an undefined value

I'm new to Ionic and I'm attempting to use the Cordova SQLite plugin. Unfortunately, I am having trouble reading a column in my code. I have followed examples, but it doesn't seem to be working. document.addEventListener('deviceready&a ...

Accessing elements from a controller in a nested ng-repeat in AngularJS

I am relatively new to the world of AngularJS and I've encountered a challenge that I can't seem to figure out. The issue lies within my nested ng-repeat view, as I have a nested comment system. Therefore, the view is built from an object structu ...

Angular 5 - Jasmine Tests explained: Encounter with the puzzling error message: "Error: Provider for the NgModule 'DynamicTestModule' is invalid, as only instances of Provider and Type are permitted"

I'm having trouble running tests on a component class. Here's the error message from the stack: Error: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [AlertModaldataCompon ...

The controller is unable to access the value bound to the controller in AngularJS

Implementing controllerAs in my directive along with bindToController. However, the bindToController parameter is coming up as undefined in the controller. See the DEMO for more details. var myApp = angular.module('myApp',[]); myApp.controller( ...