jeudi 1 septembre 2016

how to unit test a function inside Angular 1.5 component

I have created navigation with Angular 1.5 component. But facing difficulties with testing. I am new to Angular and unit testing both. Please find code on this PLUNKER

This is my component.

    module.component('firstComponent', {
    templateUrl: "1.html",
    bindings: {
      "$router": "<"
    },
    controller: function($rootScope) {

      var $ctrl = this;

      $rootScope.title = "Title from Page 1";

      $ctrl.goToNextPage = function() {
        $ctrl.$router.navigate(["Second"]);
      };

     }
    });

I am trying to test whether my current page have proper title and whether it is navigating to next page or not.

Here is my test-spec.js

      describe("Check if component is defined", function() {

      beforeEach(module("app"));

      var $ctrl;
      var router;
      var $rootscope;

      beforeEach(inject(function($componentController) {
        $ctrl = $componentController("firstComponent", {
          $router: router,
          $rootscope: $rootscope
        });
      }));

      it("are things define properly", function() {
        expect($ctrl).toBeDefined();

        expect($ctrl.goToNextPage).toBeDefined();
      });

      it("should have proper title", function() {

        expect($rootscope.title).toBe("Title from Page 1");

      });

       it("should navigate to next page", function() {

        expect($ctrl.router.navigate).toHaveBeenCalled();

      });

    });

These are the errors am getting while running the tests:

3 specs, 2 failures 1. TypeError: Cannot read property 'title' of undefined 2. TypeError: Cannot read property 'navigate' of undefined

Aucun commentaire:

Enregistrer un commentaire