简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM