繁体   English   中英

如何在Angular 1.5组件中对功能进行单元测试

[英]how to unit test a function inside Angular 1.5 component

我已经使用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个规范,两个故障1. TypeError:无法读取未定义的属性“ 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=preview

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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