2014-02-18 59 views
2

我正在爲Angular應用程序編寫一些測試,這些是我第一次使用Jasmine對Angular進行單元測試。我在構建測試以迎合函數內的各種場景(即if語句和回調)時遇到了困難。茉莉花測試多個間諜

這是我的$ scope函數,它將一個Object作爲參數,如果該對象有一個id,那麼它會更新該對象(因爲它已經存在),否則它會創建一個新的報告並推送到後端使用CRUD服務。

$scope.saveReport = function (report) { 
    if (report.id) { 
    CRUD.update(report, function (data) { 
     Notify.success($scope, 'Report updated!'); 
    }); 
    } else { 
    CRUD.create(report, function (data) { 
     $scope.report = data; 
     Notify.success($scope, 'Report successfully created!'); 
    }); 
    } 
}; 

我的測試,到目前爲止通過與一個id假的對象所以它會觸發CRUD.update方法,我再檢查被調用。

describe('$scope.saveReport', function() { 
    var reports, testReport; 
    beforeEach(function() { 
    testReport = { 
     "id": "123456789", 
     "name": "test" 
    }; 
    spyOn(CRUD, 'update'); 
    $scope.saveReport(testReport); 
    }); 
    it('should call CRUD factory and update', function() { 
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function)); 
    }); 
}); 

我明白茉莉花不允許多個間諜,但我希望能夠以某種方式測試if條件,並運行模擬測試時,對象傳中的對象太:

describe('$scope.saveReport', function() { 
    var reports, testReport; 
    beforeEach(function() { 
    testReport = { 
     "id": "123456789", 
     "name": "test" 
    }; 
    testReportNoId = { 
     "name": "test" 
    }; 
    spyOn(CRUD, 'update'); 
    spyOn(CRUD, 'create'); // TEST FOR CREATE (NoId) 
    spyOn(Notify, 'success'); 
    $scope.saveReport(testReport); 
    $scope.saveReport(testReportNoId); // TEST FOR NO ID 
    }); 
    it('should call CRUD factory and update', function() { 
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function)); 
    // UNSURE ON THIS PART TOO 
    }); 
}); 

我讀過的東西有關使用.andCallFake()的方法,但我看不出這是怎麼跟我的設置工作。任何幫助真的很感激。

+1

您是否嘗試了另一種語法'jasmine.createSpy()'? – glepretre

+0

茉莉花2增加了在測試過程中重置間諜的能力,可能會給你所需要的東西?在之前的版本中,我只爲其他情況創建了單獨的測試。 – VeteranCoder

回答

1

看來你應該先決定你需要測試什麼。如果你想簡單地測試當id存在時調用update,或者在不調用create時調用create,那麼你應該只用這些條件來構造it函數。以前每個人都是這些事情的錯誤地方。

it('should call CRUD factory and update', function() { 
    spyOn(CRUD, 'update'); 
    $scope.saveReport(testReport); 
    expect(CRUD.update).toHaveBeenCalledWith(testReport, jasmine.any(Function)); 
}); 
it('should call CRUD create', function() { 
    spyOn(CRUD, 'create'); 
    $scope.saveReport(testReportNoId); // TEST FOR NO ID 
    expect(CRUD.create).toHaveBeenCalledWith(testReport, jasmine.any(Function)); 
}); 

只有在每次測試之前,你應該在每一個你應該做的事情之前。

希望這有助於!