簡體   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