What is the best way to test an Angular directive that has a dependency on another controller in Angular version 1.3.14?

Trying to write Jasmine tests for a directive that needs a parent directive to be present. Came across this question: Testing directives that require controllers, but it seems outdated (Angular 1.1.5 I think) and the plunker doesn't work with newer versions of Jasmine (2.2.1) and Angular (1.3.14). Getting this error:

TypeError: undefined is not a function
    at Object.<anonymous>         (http://run.plnkr.co/AHQtPtvSezB4DsnJ/appSpec.js:18:33)

The code snippet:

var app = angular.module('plunker', []);
app.directive('foo', function() {
  return {
    restrict: 'E',
    controller: function($scope) {
      this.add = function(x, y) {
        return x + y;
      }
    }
  };
});

app.directive('bar', function() {
  return {
    restrict: 'E',
    require: '^foo',
    link: function(scope, element, attrs, foo) {
      scope.callFoo = function(x, y) {
        scope.sum = foo.add(x, y);
      }
    }
  };
});

And the test case:

describe('Testing directives', function() {
  var $scope, $compile, element;

  beforeEach(function() {
    module('plunker');

    inject(function($rootScope, _$compile_) {
      $scope = $rootScope.$new();
      $compile = _$compile_;
    });
  });

  it('checks if callFoo works correctly', function() {
    // Arrange
    var element = $compile('<foo><bar></bar></foo>')($scope);
    var fooController = element.controller('foo');
    var barScope = element.find('bar').scope();
    spyOn(fooController, 'add').andReturn(3);

    // Act
    barScope.callFoo(1, 2);

    // Assert
    expect(barScope.sum).toBe(3);
    expect(fooController.add).toHaveBeenCalledWith(1, 2);
  });
});

Here's the updated plunker:

http://plnkr.co/edit/bC5BY81x0hi576xwSdyo?p=preview

Realize this may not be the ideal design, but currently stuck with it. Thanks!

Answer №1

Method #3 from the aforementioned question on SO was the perfect solution for my issue. It turns out I just needed to read a bit further.

Link to the helpful answer

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

"VueJs and ChartJs work together to create single file components, but the computed property is only rendered in Vue Dev Tools when the component is

Currently, I am working on a single file component that utilizes Chart.Js to display a basic visualization of some hardcoded data. The Chart.Js library is being called from a CDN placed in the head section of my index.html file. The project is based on th ...

What is the best way to include an ID parameter in a $ajax GET request?

Real-life Dilemma I've been grappling with an issue for the past 4 hours - I'm attempting to send an http get request with the user ID as a parameter. Despite trying numerous examples found online, I continue to encounter this pesky error on the ...

Achieving functionality with Twitter Bootstrap's "Tabs" Javascript in a Ruby on Rails application

Encountering a JavaScript issue within a Rails application. Although Twitter's documentation is very clear, I'm still struggling to make dynamic tabs work (tab switching and dropdown). I even went ahead and copied their source code, downloaded t ...

Connecting React with an HTML element that is not within the React DOM

Dealing with a complex MathJax rendered equation containing interactive elements can be quite tricky, especially when using it within a react component. MathJax and react don't always play nice together. Currently, I have a react app that displays a ...

The function is not being triggered, should I include a window.load event?

Seeking to modify the CSS styles of an element upon click. ryan.js function ryanClicked(id){ document.getElementById(id).style.color = "blue"; alert("Asdsa"); } product.html <head> <script src="ryan.js"></script> </head ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Message successfully sent despite Ajax failure

Hello everyone, I'm currently facing an issue while trying to send a message using the form craft plugin. The error message that I am encountering is " 504 (Gateway Time-out)" along with some technical details: send @ jquery.js:4 ajax ...

Scope Problem with Angular-UI-Bootstrap Modal Dialog

Hello everyone, I am a beginner in AngularJS and I am currently exploring ways to display a modal dialog for handling $http call errors using Angular-UI-Bootstrap. My goal is to pass the error text from the calling controller to the $scope used by the dial ...

How can I enable pagination in Datatables when the table HTML is generated using Angular after the drawCallBack function?

Below is the drawCallBack function I have implemented: "fnDrawCallback": function( oSettings ) { console.log("dt redrawn"); var selector = $("#example_table"); console.log(selector); function recompileForAn ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Reactive JS memory leakage occurring from recurring calculations utilizing setInterval

I'm currently working on a task where I need to run a calculation every 5 seconds and update a component's state with the result using a setInterval timer. It seems that the updateCalculation() function is being called every 5 seconds, but I&apos ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

Change to JSONArray using angularjs

Here is a json object: "values": [ {"name": "name1"}, {"name": "name2"}, {"name": "name3"} ] I want to convert it into this format: values: ["name1", "name2", "name3"]; Can this conversion be done in AngularJS or any other JavaScript functi ...

A more efficient method for tallying values within an object (JavaScript, React)

Is there a more efficient way to determine the count of items with a specific key/value pair in a React state? When the list is large, this method may become a bottleneck. To illustrate the question, consider the following simplified example: class App ...

What are the steps to integrate dynamic data into chartjs?

Can you assist me in understanding how to dynamically populate Chartjs with data from a json file? Specifically, I am looking to dynamically fill the labels and data fields. Sample JSON File <<< [ { "EFICAZ_TAB_ITEM_ID":1, " ...

Looking for a speedy solution with a [PHP function] that needs to be converted to a [JavaScript function

Looking for a quick favor - can anyone help me out with this: static function make_url_safe($z){ $z = strtolower($z); $z = preg_replace('/[^a-zA-Z0-9\s] /i', '', $z); $z = str_ireplace(' ', '-', $z) ...

Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the ...

Creating a Node API that can patiently listen for external data

My current project involves building a server that fetches data from an external API and returns it to the endpoint localhost:3000/v1/api/. However, I'm facing a challenge where the data retrieval process takes approximately 2 seconds, leading to empt ...