Why is Jasmine throwing an error when I try to use getElementsByTagName(...)?

HTML:

<ul id="listONE">
      <li class="{{isSel}}" ng-repeat="person in people" ng-click="selPersonToChange(this)">{{person.name +" - "+ person.city}}</li>
</ul>

A snippet from my script.js using AngularJS (1.3.1):

mymod.controller("maincontroller", function($scope){

    $scope.people = [
        { name: "name1", city: "city1" },
        { name: "name2", city: "city2" },
        { name: "name3", city: "city3" }
    ];

    $scope.oldIndex = 0;
    $scope.oldPerson = 0;
$scope.selPersonToChange = function(){

    $scope.personToChange.person = this.person;
    $scope.personToChange.index = this.$index;

    lis = document.getElementById("listONE").getElementsByTagName("li");//this line is causing an error
    for(i=0; i<lis.length; i++){ lis[i].className = ""; }
    lis[this.$index].className = "selected";
    return true;        
}

Jasmine TDD test case:

Jasmine tdd.js:

describe("myApp", function(){

    beforeEach(module("mymod"));

    describe("maincontroller", function(){

        var scope;
        var ctrl;
        var els;
        beforeEach(inject(function($rootScope, $controller, $compile){
            scope = $rootScope.$new();
            ctrl = $controller("maincontroller", {$scope:scope});
            els = $compile('<ul id="listONE"><li class="{{isSel}}" ng-repeat="person in people" ng-click="selPersonToChange(this)">{{person.name +" - "+ person.city}}</li></ul>')(scope);
            scope.$digest();   
            console.log(els.html());

        }));

        it("Is ul #listONE null or undefined?", function(){
            expect(scope.selPersonToChange()).toEqual(true);
        }); 


    });

});

The issue lies with the line "document.getElementById('listONE')", which indicates that "listONE" does not exist.

Answer №1

In order for your controller to locate that element, it is essential to instruct AngularJS to "load" a view within your test scenario. Simply instantiating the controller does not initiate loading of your HTML content.

If your application utilizes the ngRoute module, consider injecting and utilizing the $location service during testing to force the loading of a specific path. By setting a path like /some/path that corresponds to your controller and HTML, you can execute $location.path('/some/path') followed by $rootScope.$apply() prior to conducting assertions.

If ngRoute is not employed, an alternative approach could involve compiling a template defined within your tests that contains elements like

<div ng-controller="maincontroller">...</div>
.

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

Encountering an issue in next.js with dynamic routes: getting a TypeError because the property 'id' of 'router.query' cannot be destructured since it is undefined

I am working on creating a dynamic page in next.js based on the ID. Here is the basic structure of my project: File path: app/shop/[id]/page.tsx This is the code snippet: "use client" .... import { useEffect, useState } from 'react' ...

Emphasize the present selection along with all prior items in a menu

Attached is my menubar for a unique web design concept I am working on. My webpage is designed as a fully scrollbar page shift type, meaning it is a single page containing six sections that are scrollable by selecting menu items. Currently, when I click ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Redirecting a user to the logout page using Angular.js, Express.js

Example Code (implementing passport-local on angular-fullstack): app.get('/logout', function(req, res) { req.logout(); console.log('testing123'); res.redirect('/login'); } Upon execution of this code, the URL bri ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...

The functionality of a button within a web component is restricted to only trigger the click event once after it has been

I am facing an issue with my class that includes three buttons for navigating the app. The event listeners I add to these buttons in the connectedCallback method only work once. When I click one of the buttons, like the next button, it changes the attribut ...

Vue transition isn't functioning correctly without the specified mode parameter of 'out-in'

I'm struggling to comprehend why the transition doesn't smoothly roll from top to bottom without mode="out-in". When using out-in, it rolls as expected (albeit with a delay), but without it, the transition just suddenly appears after rolling dow ...

An issue has been encountered with the default selection in a dropdown menu

Struggling to make the initial option of a select box "selected" upon page load. Check out the code on Plunker In the provided plunker example, the select box appears empty when the page loads even though the deal model has a default category value. What ...

Issue on WordPress where JQuery is undefined causing continuous refreshing on IPhone devices

My wordpress website is performing well in most browsers, including some mobile ones. However, when accessed on an IPhone, the homepage keeps refreshing in a continuous loop. Even after emulating an IPhone using Chrome developer tools, the issue persists. ...

Create waypoints on multiple elements

I am working on implementing a unique feature using a div tag with the class "dipper." <div class = "dipper"> <p>Peekaboo</p> </div> As part of this implementation, I have included a script that triggers the display of the "dipper ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

The file upload issue with FormData append in CodeIgniter is causing errors

My current challenge involves uploading files using AJAX to my CodeIgniter based website. Unfortunately, I am encountering an issue where I cannot retrieve the file field value in the controller. This results in an error message stating "Undefined index: & ...

Load annotations from a JSON file with Annotator.js

Seeking assistance with incorporating annotations into my website using annotator.js. I have been encountering difficulties getting it up and running successfully. My goal is to display highlighted annotations upon page load, but I keep receiving a JavaSc ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

Using jQuery to arrange information from an API into a table

Currently, I am in the process of learning jQuery as it is a new concept for me. I have attempted to make a request to an example API and received an array of objects that need to be listed in a table. However, I am facing difficulty in sorting it within t ...

How can I create my own unique scrolling behavior in JavaScript?

Looking to create a similar effect as seen on this website: where the vertical scrollbar determines the movement of the browser "viewport" along a set path. I believe that using Javascript to track the scroll bar value and adjust background elements acco ...

Tips to instantiate an object of a different JavaScript class in Node.js

Hey there! I'm having trouble creating an instance of ProfileComparator in a different JavaScript file called index.js. Can someone help me resolve this error? strategy.js var cosineUtils = require("./jscosine"); var ProfileComparator = function(al ...

Patience is key when letting AJAX calls complete their execution in jQuery functions

In each of my 3 functions, I have a synchronous AJAX call. Here is an example: function() { a(); b(); c(); } a() { ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '&apos ...

When utilizing multer for handling multipart data, hasOwnProperty appears to become undefined

Below is the code snippet I am currently working with: var express = require('express'); var mongoose = require('mongoose'); var bodyParser = require('body-parser'); var multer = require('multer'); var user = requir ...