Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example:

Here is the controller file:

angular.module('balrogApp.requests', [
  /* Dependencies */
])
  // Routes configuration
  .config(['$routeProvider', function($routeProvider) {
    /* $routeProvider configuration */
  }])
  .controller('requestsController', function(Requests, Users, Projects, RequestsComments, CostEstimations,
                                             Regions, growl, $route, $rootScope, $scope, $location) {
    this.test = 'test42';

/* ... */

});

This is the test file:

describe('requestsController', function() {
  beforeEach(module('balrogApp.requests'));

  var ctrl;
  beforeEach(inject(function($controller) {
    ctrl = $controller('requestsController');
  }));

  it('should have test = "test42"', function(){
    expect(ctrl.test).toBe("test42");
  });
});

However, I encountered this error:

Chrome 43.0.2357 (Windows 7 0.0.0) requestsController should have test = "test42" FAILED Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- requestsController http://errors.angularjs.org/1.4.7/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20requestsController at C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:68:12 at C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4289:19 at Object.getService [as get] (C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4437:39) at C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4294:45 at getService (C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4437:39) at invoke (C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4469:13) at Object.instantiate (C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:4486:27) at C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular/angular.js:9151:28 at C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular-mocks/angular-mocks.js:1882:12 at Object. (C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:6:12) Error: Declaration Location at window.inject.angular.mock.inject (C:/Users/aazor102115/Desktop/Dev/Balrog/bower_components/angular-mocks/angular-mocks.js:2409:25) at Suite. (C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:5:14) at C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:1:1 TypeError: Cannot read property 'test' of undefined at Object. (C:/Users/aazor102115/Desktop/Dev/Balrog/tests/requests.js:10:16) Chrome 43.0.2357 (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.108 secs / 0.087 secs)

Answer №1

When it comes to the $scope in your controller, it's important to remember that it is considered a "local" variable specific to the controller instance and not stored in the dependency injection container. You will need to provide it yourself, such as demonstrated below:

beforeEach(inject(function($rootScope, $controller) {
    ctrl = $controller('requestsController', { $scope: $rootScope.$new() });
}));

It's advisable to clean up after each test by destroying the scope since you are creating a new one:

var scope;

beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    ctrl = $controller('requestsController', { $scope: scope });
}));

afterEach(function() {
    scope.$destroy();
});

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

Transform seconds into an ISO 8601 duration using JavaScript

Dealing with ISO 8601 durations can be quite tricky. Efficiently converting seconds to durations is my current challenge, especially in JavaScript. Stay tuned for my solution and the Jest test script coming up next. ...

Alternative solution to avoid conflicts with variable names in JavaScript, besides using an iframe

I am currently using the Classy library for object-oriented programming in JavaScript. In my code, I have implemented a class that handles canvas operations on a specific DIV element. However, due to some difficulties in certain parts of the code, I had t ...

What impact does async await have on the asynchronous nature of JavaScript?

Although JavaScript is synchronous, we utilize callback promises and async-await to achieve asynchronous behavior. However, with async-await, the code waits for the await statement to be completed before proceeding to the next statement, which may seem s ...

Out of the box, Next.js is equipped with a standard error message stating: "TypeError: Cannot read properties of null (reading 'useContext')"

After just setting up next.js for my upcoming website, I ran into some unexpected errors while trying to host it with "next". The specific error message I encountered was: TypeError: Cannot read properties of null (reading 'useContext') This iss ...

What is the process for modifying a Gist on GitHub?

Trying to update my Gist from another website using my gist token has been unsuccessful. Retrieving a gist with GET was successful, but updating it with PATCH is not working. I don't believe authentication is the issue since retrieving the gist displ ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Having trouble inserting a Button element into a li parent element

I'm attempting to insert a button inside an li element using the .appendChild method, but for some reason, it's not working. I also tried changing the parent's inner HTML. let inputElement = document.querySelector('#input'); let ...

Enhance your user interface by customizing the expand icon in the React material

Currently, I am utilizing Material-table with a focus on Tree-data. You can find detailed information about this feature here: https://material-table.com/#/docs/features/tree-data. While attempting to implement the provided example, I am encountering diff ...

Struggling with implementing Vue.js for making a task list using Bootstrap 5

I'm trying to get the hang of Vue.js. I've been working on setting up a to-do list where users can input tasks, but I'm having trouble getting the list to display correctly when I define the method. It seems like my add() function isn't ...

AngularJS is throwing an error because the term "grunt" has not

Today is the day I embark on my journey with Grunt for testing my JavaScript code. All the necessary grunt modules have been successfully installed and are documented in a json file called package.json. { "name": "LarissaCity", "private": true, ...

After the update, Material UI is causing a TypeError by throwing an error stating that it cannot read the property 'muiName' of an

After updating from "material-ui": "^1.0.0-beta.38" to "@material-ui/core": "^1.3.0", I made changes to imports, ran npm install, removed node_modules and even deleted package-lock.json. However, I continue to encounter the cryptic error message TypeError: ...

What is the process for implementing a CSS theme switch in a CHM file and ensuring that it remains persistent?

Welcome to my tech world Greetings! I am a tech writer with a side interest in scripting JavaScript/jQuery for our help file (CHM file). While I consider myself a beginner in JS scripting, I have ventured into the realm of dynamic theme swapping within CH ...

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Creating dynamic canvas elements with images using HTML and JavaScript

Currently, I am working on a unique project involving a canvas filled with dynamic moving balls. This project is an extension or inspired by the codepen project located at: https://codepen.io/zetyler/pen/LergVR. The basic concept of this project remains t ...

Combine the remaining bars by stacking the highest one on top in Highchart

Making use of stacking to display the highest value as the longest column/bar, with smaller values being merged within the highest one, can create a more visually appealing stack chart. For example, when looking at Arsenal with values of 14 and 3, ideally ...

Troubleshooting AngularJS expression issues when using ng-src within JSF framework

In this particular AngularJS module, the products array is defined with 2 product objects that will be assigned as a property of the controller. (function () { var app = angular.module('myApp', []); var products = [ { ...

The ng-repeat ng-switch combination is not functioning as expected

My data can be simplified to the following in my code: function DemoCtrl($scope) { $scope.myData= [ {text: "blah", other: 3, V: 'caseOne'}, {text: "blah", other: 3, V: 'caseTwo'}, {text: "blah", other: 3, V ...

Trouble with the $.inArray function

Encountering an issue with storing objects into an array. However, when attempting to verify the existence of an object using $.inArray, it consistently returns -1. The code is written in AngularJS. <input name="{{question.number}}" ng-clic ...

Guide on inserting text input value into the href attribute of a hyperlink

Lately, I've been facing an issue that has been troubling me for the past few hours. I have a search input field where users can enter text and click send. The entered text should then be added to the href attribute and sent to the results page for qu ...

React-highlightjs failing to highlight syntax code properly

I'm currently using the react-highlight library to highlight code snippets in my next.js application. However, I've encountered an issue with the code highlighting when using the a11y-dark theme. https://i.stack.imgur.com/ip6Ia.png Upon visitin ...