如何在Angular 1.5组件中对函数进行单元测试

how to unit test a function inside Angular 1.5 component

本文关键字:函数 单元测试 组件 Angular      更新时间:2023-09-26

我已经用Angular 1.5组件创建了导航。但面对测试的困难。我是Angular和单元测试的新手。请在此PLUNKER上查找代码

这是我的组件。

    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"]);
      };
     }
    });

我正试图测试我当前的页面是否有适当的标题,以及它是否导航到下一页。

这是我的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();
      });
    });

这些是运行测试时得到的错误:

3个规格,2个故障1. 类型错误:无法读取未定义的属性"title"2. TypeError:无法读取未定义属性" navigate "

您的测试中有一些错误。

首先,你需要注入服务$componentController$rootScope。之后,你需要使用$componentController服务实例化你的控制器:

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

然后你可以测试一些功能:

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

要测试导航函数,你必须在路由器上创建一个间谍,执行函数$ctrl.goToNextPage()并在间谍上断言:

let routerSpy = spyOn(router, "navigate");
...//you must instantiate your controller here as shown above
$ctrl.goToNextPage();
expect(routerSpy).toHaveBeenCalled(); 

我已经更新了你的Plunker,你可以看到完整的代码:

https://plnkr.co/edit/TiuXM5?p =预览