Jasmin, the variable $q is not defined

As I explore AngularJS examples online to grasp its functionality, I am attempting to test using Jasmine as demonstrated in the examples. In my spec file, I have:

var Person = function (name, $log) {
    this.eat = function (food) {
        $log.info(name + " is eating delicious " + food);
    };
    this.beHungry = function (reason) {
        $log.warn(name + " hungry " + reason);
    };
};

var bob = new Person();

describe("describe", function () {
    it("$q", function () {
        var pizzaOrderFulfillment = $q.defer();
        var pizzaDelivered = pizzaOrderFulfillment.promise;

        pizzaDelivered.then(bob.eat, bob.beHungry);

        pizzaOrderFulfillment.resolve("resolved");
        $rootScope.$digest();

        expect($log.TypeInfo.logs).toContain(["resolved"]);
    });
});

I encountered

ReferenceError: $q is not defined

It appears that I may be misusing Jasmine. Currently, I am writing all my Angular and Jasmine code within the spec.js file. Previously, when I had the Angular code in a separate file, my spec.js file couldn't locate it. This is likely due to a lack of setting dependencies for proper loading order, as I am just beginning to delve into this realm.

Edit, corrected the mistake of not referencing $q properly which caused the ReferenceError.

Answer №1

One issue could be not including the $q service in your unit test setup.

To fix this, make sure to inject it in the beforeEach block:

var q;
beforeEach(inject(function($q) {
    q = $q;
}));

Then, you can use it in your unit test like this:

describe("Testing", function () {
    it("should work with $q", function () {
        var pizzaOrderFulfillment = q.defer();
        var pizzaDelivered = pizzaOrderFulfillment.promise;

        pizzaDelivered.then(bob.eat, bob.beHungry);

        pizzaOrderFulfillment.resolve("resolved");
        $rootScope.$digest();

        expect($log.TypeInfo.logs).toContain(["resolved"]);
    });
});

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

Leveraging row values within the ng-grid column cellTemplate

I am currently attempting to include a column in an ng-grid table that links to another page. The link should contain one of the values from each row. Here is what I have tried so far: $scope.columns = [ {field:'id', displayName:'#' ...

retrieve information instantly on AngularJS by utilizing $http or $resource

I designed a plugin for field customization. angular.module('ersProfileForm').directive('ersProfileEditableField', ['$templateCache', '$compile', 'profileFieldService', 'RolesService', ...

The switch/case function I implemented is functioning correctly, however, an error is being displayed in the console stating "Cannot read property 'name' of null"

Check out the live codepen demo here After selecting "elephant" from the third dropdown, the console.log(brand.name) displays "elephant" as expected and executes the rest of the switch statement successfully. However, there seems to be a console error oc ...

Displaying a text in a Django template as a JSON entity

I am currently facing a challenge with an angular app that sends JSON data to a Django backend. The Django application saves the JSON data into a database and later retrieves it to send it back to the angular app. However, I am struggling to get this entir ...

Issue with jQuery: Function not triggered by value selection in dynamically created select boxes

I am in need of some assistance with my code that dynamically generates select drop down menus. I want each menu to trigger a different function when an option is selected using the "onchange" event, but I am struggling to implement this feature. Any hel ...

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. ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Order of execution and loading of JavaScript files in Webkit threading

I'm currently working on creating an XSS widget and I'm encountering some issues specifically with Webkit browsers when loading external JavaScript files that I'm appending to the DOM. Here's how it's set up: Widget.js appends 3 ...

Prevent premature termination of slow HTTP requests in Node.js/Express server

Having an issue with long duration http requests in my React/Nodejs application. Whenever a request takes more than 4 minutes to respond, it gets aborted before reaching the client. Could there be a timeout setting for requests or something else I am overl ...

What is the best way to incorporate JavaScript code using Django tags in a Django template?

Situation: In my Django 1.9 project, I have a JavaScript loop that fetches JavaScript code stored in the database. This JavaScript includes some Django tags that I need to load when the script is inserted into my template. Here is the function: {% extends ...

unable to retrieve / interpret data from herdsmen using fetch

When sending a request to a node server, the server responds with headers and a blank body. Despite being able to view the headers in the network activity panel within dev-tools, I faced difficulties reading them using the following code: let uploaded ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

Exploring the contrast between RFC and RFCE in the realm of ReactJS

As a newcomer to Reactjs, I'm curious about the distinction between "react functional component" and "react functional component export". Can someone help explain? Below is an example of a react functional component: import React from 'react&apo ...

Tips on obtaining the element's ID as a function parameter

I am currently learning front-end development and I am just starting to delve into JavaScript. Recently, when I tried to execute a piece of JavaScript code from the backend by passing some element ids, I encountered an error that says Cannot read property ...

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Discover the steps to inserting an icon into a tab using AngularJS

Hello, I am a beginner in angular js. Can someone please guide me on how to include an icon in a tab using angular js? Here is my current code: <tabset panel-tabs="true" panel-class="{{demoTabbedPanelClass}}" heading="{{demoTabbedPanelHeading}}"> ...

Unable to retrieve the $onAuth property with angularfire

I am currently working on integrating firebase auth into my app. The login controller is functioning properly, but I am facing an issue where the user gets logged out immediately after logging in. .controller('LoginCtrl', function ($scope, $loca ...

sanitizing user input in an AngularJS application

I created a feature in angular using ng-repeat <ul class="messages"> <li ng-repeat="e in enquiries"> <img src="/img/avatar.jpg" alt=""> <div> ...

Swap the value of a button's text using a dropdown list when clicked in VueJS with TypeScript

I have a button with a click event that opens a dropdown list. I would like for the button text to be updated and for the selected option to be removed from the dropdown list when the user makes a selection. Currently, using {{interestSortingOptions.label} ...

Updating the time component of a datetime object using Angular's HTTP method

I'm facing a strange bug with my API interaction through AngularJS. When trying to update something, I encounter the following code snippet: console.log('updated: ', event.startsAt); $http({ method: 'PUT', url: baseurl ...