Exploring Jasmine and AngularJS: Testing a factory function in the context of dependency injection

Looking to create a unit test for a simple factory that calculates the sum of two numbers.

    (function () {
    "use strict";

    angular
       .module("math")
        .factory("addservice", [addTwoNumbers]);

    function addTwoNumbers(a, b) {
        return a + b;
    }
    return { add: addTwoNumbers };
})();

Here's my test spec progress so far.

    describe('adding two numbers', function () {
    var addService;

    beforeEach(function () {
        module('math');
        inject(function ($injector) {
            addService = $injector.get('addservice');
        });
    });
    it('should add two numbers and equal 2', function () {
        var result = addService.add(1, 1);
        expect(result).toBe(2);
    });
});

Encountering a TypeError: addService.add is not a function when running the test. Before, we had a different factory structure to avoid minification issues with parameter names getting muddled. However, the refactored code seems to require referencing the addTwoNumbers function in a different way. Any insight on how to address this would be appreciated.

Answer №1

After some investigation, I finally identified the issue with this particular example. By making some adjustments to my factory, I was able to simplify my unit test by directly calling the twoNumbersAddedTogether property after obtaining the factory reference. Below, you can see the updated unit test and factory code.

Factory Code

(function () {
    "use strict";

    angular
    .module("math")
    .factory("addservice", [addTwoNumbers]);

    function addTwoNumbers() {

        return {twoNumbersAddedTogether: dotheMath}

        function dotheMath(a,b) {
            return a + b;
        }
    }
})();

Unit Test Code

describe('adding two numbers', function () {
var addService;

beforeEach(function () {
    module('math');
});

beforeEach(inject(function (_addservice_) {
    addService = _addservice_;

}));

it('should add two numbers', function () {
    var result = addService.twoNumbersAddedTogether(1, 1);
    expect(result).toBe(2);
});});

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

Looking to generate a computed attribute?

Trying to adjust the font size of text using a dropdown and so far it's working as expected. However, is there a more efficient way to achieve this, such as using a computed property or watcher? I'm not sure how to go about implementing that. He ...

What is the best way to utilize the each method within jQuery plugins?

I am relatively new to JavaScript and jQuery plugin development, so please bear with me if this question seems silly. I am struggling with a particular aspect of the following plugin script: (function($){ $.fn.test = function(){ var containe ...

The Node.js server seems to be continuously loading without producing any output

I've been struggling with getting my server to function properly. Whenever I send post data, the page just keeps loading and doesn't display any results. Here is a snippet of my Node.js file: var http = require('http'); var url = requi ...

I am currently utilizing AngularJS alongside Django-cors-headers, which results in the restriction of certain actions for cross-origin requests that necessitate preflight

My Django local server is running on port 8000, and I have a local Nginx server loading an HTML page on port 2080. To resolve cross-domain errors, I have installed the django-cross-header package. In my settings.py, I have configured django-cross-header ...

Struggling with linking my Angular Controller with my View and experiencing difficulty establishing a connection

I'm encountering an issue while attempting to link a controller to my view. The error I keep receiving is as follows: Error: ng:areq Bad Argument Argument 'TestAppCtrl' isn't a function, received undefined Here's the content ...

Angular 2 module that is loaded lazily - service does not follow singleton pattern

After successfully implementing lazy loading modules into my application, I have ensured that the app.module.ts is properly configured. @NgModule({ declarations: [ AppComponent, HeaderComponent, HomeComponent ], imports: [ BrowserMod ...

Ways to retrieve and contrast the border style of an image utilizing javascript

I'm currently attempting to identify images on my webpage that have the style border: 1px #c6c6c6 solid; let images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { if (images[i].style.border === "1px ...

Insert some text into the div element. Create a new line

I'm looking to make a specific text on my webpage trigger a new line when displayed in a div. I've been struggling to figure out how to accomplish this: var original= "the text @n to change"; var changed = original.replace(/@n /g, '\ ...

Load elements beforehand without displaying them using a div

In order to efficiently manipulate my Elements using jQuery and other methods, I am exploring the idea of preloading them all first. One approach I have considered is creating a div with CSS display set to none, and placing all the elements I need for my w ...

Display solely the error message contained within the error object when utilizing the fetch API in JavaScript

I am facing an issue in logging the error message to the console while everything else seems to be working fine. Specifically, I am unable to log only the message such as "email exists" when the email already exists in the system. const submitHandler = a ...

AngularJS does not support the use of $(this) syntax

I have encountered an issue while developing a Chrome extension using AngularJS. I would like to add buttons to my popup page, and I want the ancestor node to disappear when a button is clicked. Here is the code snippet: in popup.html <div class="dea ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...

Tips for dragging and dropping a file attachment directly into your web browser

Google has recently introduced this feature to Gmail, and it doesn't need you to download any additional plugins. This feature is compatible with both Firefox and Chrome browsers, but unfortunately not with Internet Explorer. ...

Color buffer can cause WebGL rendering to fail

<!DOCTYPE html> <html> <body> <canvas id="ctx" width="300" height="300"></canvas> <script> //Receiving Webgl Context var ctx = document.getElementById("ctx"); var webgl = ctx.getContext("exp ...

Break down for me what Json is in a way that a five-year-old could understand

Let me clarify one thing, I may not be a Javascript expert but I'm far from being 5 years old. Json is one concept that's been confusing me lately as I dive into the world of programming. Can someone please explain json to me in a simplified mann ...

Elements that are added dynamically do not contain any space between each other

I have a markup template that looks like this. <template id="unsequenced-template"> <button type="button" class="btn btn-primary railcar"></button> </template> Then, I use the following JavaScript ...

Issue with fulfilling Ajax promises

How can I properly use a promise to compare the current logged-in user with a field from a list in SharePoint? function compareCurrentUserWithListObject() { var userProp = this._userProfileProperties; var userName = userProp.get_userProfilePropertie ...

Using Angular to retrieve data from a JSON file correlating with information in another JSON file

Just starting out with angular and facing a problem where I'm unsure of the best approach to setting up this code efficiently. I have 2 JSON files: images.json { "imageName": "example.jpg", "imageTags": ["fun","work","utility" ...