What is the best way to instruct PhantomJS to pause until an AngularJS $resource is resolved before proceeding with testing the data it returns?

I am currently working on an AngularJS controller test script that utilizes PhantomJS. The purpose of the test is to check if the controller successfully loads "users" data from a database through a RESTFul web service using AngularJS' $resource service. However, I am facing an issue where the test fails because the $resource (which returns a promise) has not been resolved by the time the test runs. Can anyone suggest the correct approach to handle this delay in order for the test to pass? Below is the code snippet:

CONTROLLER:

.controller('MainCtrl', function ($scope, Users) {
    $scope.users = Users.query();
    $scope.sortField = 'lastName';
    $scope.reverseSort = true;
})

SERVICE:

angular.module('clearsoftDemoApp').factory('Users', function ($resource) {
    return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users', {}, {
        query: {method: 'GET', isArray: true}
    });
});

TEST:

describe('Controller: MainCtrl', function () {

// load the controller's module
beforeEach(module('clearsoftDemoApp'));

var MainCtrl, scope;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
        $scope: scope
    });
}));

it('should retrieve a list of users and assign to scope.users', function () {
    expect(scope.users.length).toBeGreaterThan(0);
});
});

Answer №1

To effectively test the controller, you must mock the factory call and then pass the mock to the controller:

beforeEach(inject(function ($controller, $rootScope) {
    var users = { query: function() { return [{}]; } };
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
        $scope: scope,
        Users: users
    });
}))

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

Ways to display a vertical scrollbar within a select box

I'm currently working with an Angular select box and I'm looking to display a scroll bar if there are more than 5 data entries. <select class="form-control" data-ng-model='projectListData.appVersion' ng-selected ng-options="v.versio ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

The issue lies with the event.target.name property - it appears to be inconsistent, working at times but failing to read properly at others

Whenever I attempt to click the button, I encounter an error. Interestingly, it seems to work on some occasions and fails on others. import React from 'react'; class Profile extends React.Component{ constructor(){ super(); th ...

Comparing the benefits of expanding/collapsing all to focusing on individual items

Encountering an issue with expanding and collapsing a menu. The goal is to achieve two functionalities: First, to expand or collapse all items in the menu. The current implementation seems to be working correctly with the following code: $("#expandAll dt ...

Send the express() app variable between files

Hey everyone, I understand there are many similar posts here, but unfortunately I'm still struggling with my issue. Within my server.js file, I have defined my app variable and implemented some configuration: var app = express(); ... In another fil ...

Struggling to create an AngularJS directive

My attempt to create a directive seems to be failing as the directive function is not being triggered. index.html <div ng-repeat="que in questions.Cars"> <question-dir>print from direcetive</question-dir> &l ...

The Importance of Node JS Callback Functions

Struggling to grasp the concept of callbacks? Check out this code snippet for authentication using MySQL. function authenticate(username, password, callback) { var query = "SELECT * from mydb.users where username='" + username + "'and BINARY ...

Invoke a function or variable based on a string parameter within a JavaScript/React function dynamically

I am currently exploring ways to dynamically call a function based on a string or reference a variable using a string. For example: import React, {useState} from 'react' const array = [ { text: 'count1', setFunctionName: &apo ...

Dealing with withdrawn requests in Express/Node.js and Angular

When a client or browser cancels a pending HTTP request, it appears that Node with Express continues to process the request, keeping the CPU busy with unnecessary tasks. Is there a way to instruct Node.js/Express to stop these pending requests that have be ...

Creating a task management application using AXIOS and VUE for easy data manipulation

I am currently working on a small app to enhance my skills in VUE and Axios. However, I am facing a roadblock when it comes to the update functionality. I am struggling to pass the ID to the form for updating and despite watching numerous tutorial videos ...

Secure your data by adding extra quotes during CSV export and IndexedDB import

Managing the export and import of an array of objects with a nested array inside involves using ngCSV, loDash, and PapaParse. This is how the array is structured: [ { arrival:"15.34.59", cancelled:"", comments:[{message: "test ...

Developing a personalized scrollable interface on React Native

Does anyone have experience with using a flatlist within a scrollview in react native? I keep receiving the warning that virtualizedLists should never be nested. As a workaround, I tried keeping the scrollview as a wrapper and adding a view with scrollin ...

Generating HTML content using JavaScript object data

I have a JavaScript file that holds data in the form of objects : let restaurant_A = { name: "BBQ place", min_order: 20, delivery_charge: 5, menu: { //First category "Appetizers": { //First it ...

Is there a way to use javascript to ensure that CSS variables stick even when overwritten by onclick events?

I have successfully implemented a method to change CSS variables using advice found here. However, I am running into an issue where the changes do not persist. After clicking on a navigation link, the styles momentarily switch to the new values but quickly ...

You can only set headers once during the initial request; any additional attempts to set headers will result in an

I encountered a specific issue with the error message "Can't set headers after they are sent". Here is the relevant code snippet: create: (request, response, next) -> socket = @app.socket # # This method will be used to call the right method ins ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

Having difficulty combining an array of JSON responses

I am working on an API call where I need to merge two objects and return them as a single entity. router.get('/reviewsavg', async (req, res) => { try { //enitityId[] is an array consisting of ID's to look up form const p ...

Ways to limit Javascript math results to two decimal points and erase previous output in one go

Working on a JavaScript multiplication task. The input provided is multiplied by 0.05. The JavaScript code successfully multiplies the input number by 0.05, but encounters some issues: The calculated value should be rounded to two decimal points. For ex ...

Attributes requested with jQuery JavaScript Library

Is there a way to dynamically add extra key-value pairs to the query string for all requests sent to the web server? Whether it's through direct href links, Ajax get post calls or any other method, is there a generic client-side handler that can handl ...