【问题标题】:how to unit test a function inside Angular 1.5 component如何在 Angular 1.5 组件中对函数进行单元测试
【发布时间】:2017-01-09 19:23:01
【问题描述】:

我已经使用 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. TypeError: Cannot read property 'title' of undefined 2. TypeError: Cannot read property 'navigate' of undefined

【问题讨论】:

    标签: javascript angularjs unit-testing testing jasmine


    【解决方案1】:

    您的测试中有一些错误。

    首先,你需要注入服务$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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-07
      • 2017-08-11
      • 1970-01-01
      • 2020-02-13
      • 2016-07-25
      • 1970-01-01
      • 2019-11-02
      • 2021-10-07
      相关资源
      最近更新 更多