0

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

1 Answer 1

1

You have some errors in your tests.

First of all, you need to inject the services $componentController and $rootScope.

After that, you need to instantiate your controller using the $componentController service:

let bindings = {$router: router};
$ctrl = $componentController('firstComponent', null, bindings);

And then you can test some functionality:

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

To test the navigate function you have to create an spy on router, execute the function $ctrl.goToNextPage() and assert on the spy:

let routerSpy = spyOn(router, "navigate");

...//you must instantiate your controller here as shown above

$ctrl.goToNextPage();
expect(routerSpy).toHaveBeenCalled(); 

I have updated your Plunker where you can see the complete code:

https://plnkr.co/edit/TiuXM5?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.