Testing with Jasmine: Object expected to equal undefined

As a beginner in AngularJS, I have just built a component that consists of a template and an associated controller.

angular.
module('beerDetail').
controller('BeerDetailController',  ['BeerSelection', '$scope', '$rootScope',
  function BeerDetailController(BeerSelection, $scope, $rootScope) {

    let beerSelected = BeerSelection.getBeerSelected();

    $scope.ok = () => { $rootScope.modalInstance.close() };
    $scope.beer = beerSelected;
    $scope.foodPairings = beerSelected.food_pairing.join(", ");

    this.getFormattedIngredients = (ingredients) => {...};

    this.getFormattedMethod = (method) => {...};

    $scope.allIngredients = this.getFormattedIngredients(beerSelected.ingredients);
    $scope.method = this.getFormattedMethod(beerSelected.method);
  }
]).
component('beerDetail', {
  templateUrl: '/components/beer-detail/beer-detail.template.html',
  controller: 'BeerDetailController',
});

To test the controller, I have come up with the following test which verifies if the beer passed into the scope matches the one retrieved by calling: BeerSelection.getBeerSelected():

describe('BeerDetailController', function() {

  it('returns the selected beer', function() {

      beforeEach(module('beerDetail'));

      let $controller;
      let scope;
      let rootScope;
      let createController;
      let beerSelection;
      let beerSelected = {
        "id": 192,
        "name": "Punk IPA 2007 - 2010",
      };

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        createController = function () {
          return $controller('BeerDetailController',
            {'BeerSelection': beerSelection},
            {'$scope': scope},
            {'$rootScope': rootScope}
            );
          spyOn(beerSelection, 'getBeerSelected').and.returnValues(beerSelected);
        };
    }));

    expect(scope.beer).toEqual(beerSelected);
    });
  });

However, running the test prompts the following error message:

Expected undefined to equal Object({ id: 192, name: 'Punk IPA 2007 - 2010' })

What could be causing this issue?

Answer №1

Don't forget to utilize the createController method in order to effectively create it. It was simply an assignment you executed in your beforeEach block.

createController();     
expect(scope.beer).toEqual(beerSelected);

This should be functioning as expected.

To register (edited from comment) :

angular.
module('beerDetail').
controller('BeerDetailController',  {your controller function}).
component('beerDetail', {
  templateUrl: '/components/beer-detail/beer-detail.template.html',
  controller: 'BeerDetailController'
....

I believe this should do the trick.

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

Dealing with reactive form controls using HTML select elements

I am working with a template that looks like this: <form [formGroup]="form"> <mdl-textfield type="text" #userFirstName name="lastName" label="{{'FIRSTNAME' | translate}}" pattern="[A-Z,a-zéè]*" error-msg ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

The attempt to fetch an additional 10 items through an AJAX call failed to meet expectations

I want to implement a feature where 10 items are loaded each time the "load more" button is clicked. Initially, I send the first 10 items and use dajaxice to load another set of 10 items everytime the button is pressed. Below is my view: def dj(request, ...

Hide the div in PHP if the active variable is null

It looks like I'll need to implement Jquery for this task. I have a print button that should only appear if my array contains data. This is a simplified version of what I'm aiming to achieve: HTML <?include 'anotherpage.php'?> ...

What is the best way to retrieve every single element stored in an Object?

On a particular page, users can view the detailed information of their loans. I have implemented a decorator that retrieves values using the get() method. Specifically, there is a section for partial repayments which displays individual payment items, as d ...

Displaying AJAX response with AngularJS

My Angular script structure is shown below: var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when ...

unable to display preview images using the youtubev3 API

Currently in the process of creating a YouTube clone using the YouTube V3 API import React from 'react' import { Link } from 'react-router-dom'; import { Typography, Card, CardContent, CardMedia } from '@mui/material'; import{ ...

The functionality of the click event does not function properly for buttons that are dynamically generated using

Upon selecting the "Keyboard layout" option, JavaScript generates buttons dynamically. However, the click event does not work with these dynamically generated buttons. This issue is likely due to the fact that the element ".prices-tier" does not exist when ...

I am unable to pass a variable through a callback, and I cannot assign a promise to a

Currently, I am facing a challenge with my code where I need to loop through a hard-coded data set to determine the distance from a user-entered location using Google's web API. The issue lies in passing an ID variable down through the code so that I ...

Tips on transferring information from React frontend Hooks to the Express backend

I'm encountering an issue when attempting to send data from my React front end, which is utilizing hooks, to my Node/Express server. Upon inspecting the request object (userLog) in the Express back end, I notice that the body content is empty. Can an ...

Getting a specific element of the "Event" object using javascript/typescript

Overview I successfully integrated a select box into my Vue.js/Nuxt.js application using Vuetify.js. I utilized the @change event to capture the selected value. <v-select v-model="selectedStartTime" :items="startTime" item ...

Guide on incorporating mouse movement while the mouse button is held down in JavaScript

For my project, I want to activate the mouse move event only when the mouse button is held down. I specifically need the action "OK Moved" to be triggered only when both the mouse button is held down and there is mouse movement. This is the code that I h ...

Error encountered in React V16.7: The function is not valid and cannot be executed

import React, { useContext } from 'react'; The useContext function is returning undefined. Error Details: Uncaught (in promise) TypeError: Object(...) is not a function Error occurred when processing: const context = useContext(UserCon ...

What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way: function (Vue, options) { Vue.$detector = new TranslatableStringDetector(); } Utilizing it within a computed property in my component is done l ...

JavaScript Error: Uncaught TypeError - The property 'remove' cannot be read because it is undefined

My modal window setup allows for opening two separate modals one after another, with the capability to close them individually (closing the second modal while keeping the first one active). (All the necessary code snippets are included below) let open_mo ...

Is the typeahead feature acting unusual - could this be a glitch?

My input field uses typeahead functionality like this: <input type="text" id="unit" name="unit" class="form-control form-input" ng-model="item.unit" autocomplete="off" typeahead-min-length="0" uib-typeahead="unit a ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

Can the placement of Vue.js methods impact the overall performance and size of the application?

I am currently working with a list component and a looping item component structured as follows: RoomList.vue <template> <ul id="TheRoomList"> <button id="TheCreateRoomButton" @click="createRoom()& ...

Can you explain the process of utilizing a JavaScript function that has been fetched via Ajax

When the AJAX function is loaded on the page, I am attempting to execute another function. The code snippet for the AJAX call: $.ajax({ type: "POST", url: "loginpersonal.asp", data: "id=<%=request("id")%>", beforeSend: function() { $("#personal ...

Issue: Attempting to access the `userName` property on an undefined object (`tem`), resulting in a TypeError while using flalist

A concern has arisen with the React Native Flatlist as it fails to render properly. What steps should be taken in this scenario? Below is the code snippet for reference: Image description available here import React, {useState, useEffect} from 'react ...