Retrieving data from a simulated angular service and making calls accordingly

I'm struggling with writing tests for a controller method that relies on an Angular service call and needs to test the code inside the .then() function afterwards.

Here's the basic concept:

// Controller

$scope.myMethod = function() {
    methodName.connect().then(
        function(returnValue) {
            if (returnValue.prop === 1) {
                $scope.callMade = true;
                $rootScope.$emit('callWasMade');
            }
        },
        function() {
            $rootScope.$emit('callWasNotMade');
        }
    );
};

I want to test calling the method on the $scope, invoke the methodName.connect() function, mock a response by overriding returnValue, and ensure the function runs normally. Something like this:

// Test

describe('connecting to method', function() {
    it('should do nothing when returnValue.prop does not equal 1', function() {
        spyOn(methodName, 'connect').and.returnValue({ prop: 2 });
        scope.myMethod();
        expect(scope.callMade).toBeFalsy();
    });

    it('should pass when returnValue.prop does equal 1', function() {
        spyOn(methodName, 'connect').and.returnValue({ prop: 1 });
        scope.myMethod();
        expect(scope.callMade).toBeTruthy();
    });
});

However, I'm encountering the error:

undefined is not a constructor (evaluating 'methodName.connect().then') (...)

Is there a way to control the output from methodName.connect in this manner?

Thank you.

Answer №1

It has been mentioned that methodName is considered a service. Therefore, the suggested approach is to mock this service within the injected controller.

One query regarding the controller - why is myMethod attached to the scope rather than directly to the controller itself (i.e., using myMethod = function() {})?

The set of code below demonstrates how this should function:

describe('connecting to method', function() {
  beforeEach(inject(function($controller, $rootScope) {
    // create a mock service linked to the controller
    methodName = {
      connect: function () {
      }
    };

    spyOn(methodName, 'connect').and.returnValue({ prop: 2 });

    scope = $rootScope.$new();
    controller = $controller('yourCtrl', {
      $scope: scope,
      methodName : methodName 
    });
  }));

  it('should do nothing when returnValue.prop does not equal 1', function() {
    // assuming myMethod is part of the controller, not the scope
    myMethod();
    expect(scope.callMade).toBeFalsy();
  });
});

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

Change from full manual control to automatic mode

Here is the link to my code: http://jsfiddle.net/yHPTv/2491/ I am experiencing an issue with the transition effect. The hidden element is supposed to slide into view from the right edge of the .block element, but instead, it just appears suddenly. .blo ...

Error: Unable to access the 'thumbnail' property because it is undefined

I have encountered a situation where I am able to access all properties except for one. I am struggling to identify what the issue might be. Here are some approaches I have tried: this.props.data.imageLinks.thumbnail this.props.data.imageLinks[thumbnail ...

Integrating JavaScript functions into TypeScript

When converting a JavaScript function to TypeScript, I encountered an issue. The function works fine in JS but in TS, I receive the following error: [ts] Cannot find name 'PasscodeAuth'. Did you mean 'passcodeAuth'? function passco ...

Troubleshooting issues with NodeJS server and client connectivity on Cpanel

I've successfully created a nodejs application that functions as a websocket server and serves a basic client webpage. The websocket is running on port 8080, and the client connects through wss://192.168.3.101:8080 when tested locally. However, when I ...

Error message 'ENOENT, open' occurs when attempting to utilize the 'uploadDir' parameter in connect-multiparty with Express 4

Currently utilizing connect-multiparty with Express4/Node/Angular. When running it locally and attempting a file upload, I encounter an 'ENOENT open' error when specifying an 'uploadDir', however it functions properly with the default m ...

Eliminate the character """ from the HTML code

Is there a way to remove the "|" between each "a" tag below using CSS, Javascript, or jQuery since I don't have access to edit the HTML directly? <span class="reportnavigation"> <span class="reportnavigationheader"> Go To Week ...

Tips for efficiently handling multiple form inputs using PHP

As part of my project, I am designing an admin panel for a distribution company. They have specifically requested a feature where they can input orders for all clients through a single page. To meet this requirement, I have created a dynamic form that gene ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

Using a React PureComponent to pass parameters from a Child component

I am facing an issue with my TodosList component that displays a list of individual Todo components. Below is the code snippet for the Todo component: export class Todo extends React.PureComponent { render() { return ( <li onClick={this.pr ...

Utilizing the static folder feature in Express on a shared hosting platform

Struggling with implementing a static folder in my Node.js+Express application, I keep encountering a frustrating 404 error. After setting up the basic structure using express project_name, here is the simplified folder layout: app.js /views \-- la ...

Exploring the functionality of two-way data binding in Angular - a beginner's guide

Transitioning from a different framework and switching from JavaScript to Angular & TypeScript has left me feeling confused about how to efficiently share data/values between components. ...

What are the steps for transitioning an Angular application from MonoRepo to PolyRepo?

Having created three separate Angular applications with individual workspaces, projects, and repositories, I am able to share modules among them using @angular-architects/module-federation. However, I am facing challenges when it comes to sharing component ...

Exploring the power of Node.js and EJS through the art of

Recently delving into the world of node.js, I encountered a puzzling issue with my EJS template. It seems that my for loop is not executing properly within the EJS template while attempting to create a basic todo app. Below is the structure of the project ...

Retrieving particular excerpts from a block of text that includes the keyword "javascript."

I have a chunk of string containing HTML source code. Currently, I am trying to read specific tags that I need using JavaScript. Since I am new to programming, I'm unsure how to proceed. Can anyone assist me with this? The issue lies in the following ...

How can you access the index of an object in Vue.js when one of its properties has been modified

Here's the Vue component code I'm working with: data: function () { return { products: [ { product_id: '', price: ''}, { product_id: '', price: ''}, ], ...

IE compatibility mode causing ckeditor dropdown to be hidden

When using the CKEditor editor bar inside a green div with another div below it, I noticed that when clicking on "font" or any other option that opens a dropdown menu, it gets hidden behind the bottom div. This issue seems to occur in browsers like Chrome ...

Troubleshooting issue with Angular nested ng-repeats and JSON request not functioning properly

I'm trying to create a nested list using ng-repeat and a JSON file: [] Pizza King North Region [] Pizza King 102 [] Pizza King 103 [] Pizza King 104 [] Pizza King South Region [] Pizza King 201 [] ...

Troubleshooting: Button Functionality Issue in HTML and Javascript

Currently, I am in the process of completing my final project for an introductory web development course. While I am very new to javascript and html, the project itself is a simple Mad Libs task. Throughout the day, I have encountered numerous issues attem ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...