簡體   English   中英

AngularJs 單元測試控制器與茉莉花測試中的甜蜜

[英]AngularJs Unit Testing Controller with sweetalert in Jasmine Testing

我正在嘗試使用 jasmine 和 karma 測試我的 angularjs 控制器,但我無法測試處於 Sweetalert 函數中的代碼塊。 我如何從我的測試類中確認測試 $scope.getCategory() 的甜蜜函數是否被調用? 這是我的控制器和茉莉花測試用例中的示例代碼。

控制器:

$scope.changeCategoryStatus = function(selectedId, selectedActive, topId) {
    sweet.show({
        title : "Kategoriyi "+(!selectedActive ? 'aktif' : 'pasif')+ " hale getirmek istiyor musunuz?",
        type : "warning",
        showCancelButton : true,
        confirmButtonColor : "#DD6B55",
        confirmButtonText : "Evet, değiştir!",
        closeOnConfirm : false,
        showLoaderOnConfirm : true,
        html : false
    }, function() {
        $http({
            method : "POST",
            url : webRootUrl+"ajax/category/setActivation",
            data : {
                "id" : selectedId,
                "active" : !selectedActive
            }

        }).then(function(response) {

            //console.log(JSON.stringify(response.data))
            if(response.data.outPutDouble==-7){
                swal("Değiştirilemedi!", response.data.outPutString,"error");
            }else{
            $scope.getCategory(topId);
            swal("Bu kategorinin durumu değiştirildi","",
            "success");
            }
        }, function myError(response) {
            swal("Bu kategorinin durumu değiştirilemedi","","error");

            //console.log("***aaa" + JSON.stringify(response))
        });


    });

}

茉莉花測試用例:

  it("changeCategoryStatus success", function () {
  $scope.changeCategoryStatus(21,true,0)

  spyOn($scope,'getCategory')
  expect($scope.getCategory).toHaveBeenCalled(); });

有沒有人之前遇到過類似的問題? 預先感謝您的幫助。

這是我在 Angular 2 應用程序單元測試中所做的

it("should delete token", () => {
  spyOn(localStorage, 'removeItem');

  // call function
  comp.deleteToken();

  // add some delay till the sweetAlert modal show up
  setTimeout(() => {
    // select the button for the activity you want to test
    let cancelSwal: HTMLButtonElement = fixture.debugElement.query(By.css(".sa-button-container > .cancel")).nativeElement;
    cancelSwal.click();

    // test your sweetAlert callback function
    expect(localStorage.removeItem).toHaveBeenCalledWith("token");
  }, 100);
});

正如你所看到的,它直截了當,沒什么特別的,

  • 調用帶有 sweetAlert 的函數
  • 使用setTimeout添加延遲以確保存在 swal 模式
  • 使用它的 CSS 選擇器選擇想要的 DOM 元素
  • 執行所需的操作(在我們的示例中是click事件)以獲取要測試的回調函數
  • 快樂測試:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM