我試圖讓使用注入組件的服務的Github的API調用 - 是的,我使用AngularJS 1.5.3。AngularJS /噶/茉莉花 - 服務電話沒有返回值
在單元測試中,我沒有收到回值(當我在瀏覽器中運行它的功能不工作)。我不確定自己做錯了什麼,希望有人能指引我走向正確的方向。
main.component.js
(function(){
angular.module("app").component("mainComponent", {
templateUrl: "/templates/main.component.html",
controllerAs: "vm",
controller: function(APIFactory, UserFactory, $state){
const vm = this;
vm.searchGithub = function(){
APIFactory.getAPI(vm.searchText).then(function(res){
res.status !== 200 ? $state.go("404", {errorData: res.data }) : (
vm.User = new UserFactory.User(res.data),
$state.go("profile", {userData: vm.User})
);
})
.catch(function(err){
$state.go("fourOFour");
});
};
}
});
})();
main.component.spec.js
describe("Main Component", function(){
var mainComponent, APIFactory, UserFactory, $httpBackend, $q, $state, $rootScope;
const addy = "https://api.github.com/users/";
beforeEach(angular.mock.module("app"));
beforeEach(inject(function(_APIFactory_, _UserFactory_, _$httpBackend_, _$state_, _$q_, _$rootScope_, _$componentController_){
APIFactory = _APIFactory_;
UserFactory = _UserFactory_;
$httpBackend = _$httpBackend_;
$state = _$state_;
$q = _$q_;
$rootScope = _$rootScope_;
$rootScope.$new();
mainComponent = _$componentController_("mainComponent", { $scope : {} });
}));
describe("Checking if the searchGithub() worked correctly", function(){
var result;
beforeEach(function(){
spyOn(mainComponent, "searchGithub").and.callThrough();
spyOn(APIFactory, "getAPI").and.callThrough();
result = {};
});
it("should make a call to UserFactory", function(){
mainComponent.searchText = "someName";
expect(mainComponent.searchText).toBeDefined();
// RESPONSE_SUCCESS does exist, I've omitted it.
$httpBackend.whenGET(addy + mainComponent.searchText).respond(200, $q.when(RESPONSE_SUCCESS));
// This is where I expect something to work
APIFactory.getAPI(mainComponent.searchText).then(function(res){
result = res;
});
$httpBackend.flush();
expect(APIFactory.getAPI).toHaveBeenCalledWith(mainComponent.searchText);
expect(mainComponent.User).toBeDefined();
});
});
});
這裏是一個方法論的問題,而不是關注你混合所有單位某些特定裝置上的 - 控制器,服務和$ httpBackend - 成一個大的混亂。當不順心的事,你不這樣做。知道它在哪一點失敗。如果你正在測試一家公司在這裏ntroller,模擬/存根其他所有服務(包括$州)。 – estus
更改'期望(mainComponent.User).toBeDefined();''到期望(mainComponent.User).not.toBeDefined();'。 – georgeawg
@estus - 我很欣賞這個好建議。你能看看我的答案,看看你是否認爲這是一個好的解決方案? –