/ / Testowanie transmisji w AngularJS i Testacular - testowanie, angularjs, jaśmin, karma-runner

Testowanie transmisji w AngularJS i Testacular - testowanie, angularjs, jaśmin, karma-runner

Używam angular-http-auth moduł przechwytujący 401 odpowiedzi. Ten moduł nadaje event:auth-loginRequired jeśli istnieje odpowiedź 401, którą można otrzymać za pomocą $ on (). Ale jak mogę to przetestować?

beforeEach(inject(function($injector, $rootScope) {
$httpBackend = $injector.get("$httpBackend");
myApi = $injector.get("myApi");
scope = $rootScope.$new();
spyOn($scope, "$on").andCallThrough();
}));
describe("API Client Test", function() {
it("should return 401", function() {
$httpBackend.when("GET", myApi.config.apiRoot + "/user").respond(401, "");
myApi.get(function(error, success) {
// this never gets triggered as 401 are intercepted
});
scope.$on("event:auth-loginRequired", function() {
// This works!
console.log("fired");
});

// This doesn"t work
expect($scope.$on).toHaveBeenCalledWith("event:auth-loginRequired", jasmine.any(Function));

$httpBackend.flush();
});
});

Odpowiedzi:

9 dla odpowiedzi № 1

Na podstawie twojego komentarza myślę, że nie potrzebujesz expect($scope.$on).toHaveBeenCalledWith(...); ponieważ zapewnia, że ​​coś naprawdę nasłuchuje zdarzenia.

Aby upewnić się, że wydarzenie zostało zwolnione, musisz przygotować wszystko, co konieczne, a następnie wykonać akcję prowadzącą do transmisji wydarzenia. Myślę, że specyfikację można opisać w następujący sposób:

it("should fire "event:auth-loginRequired" event in case of 401", function() {
var flag = false;
var listener = jasmine.createSpy("listener");
scope.$on("event:auth-loginRequired", listener);
$httpBackend.when("GET", myApi.config.apiRoot + "/user").respond(401, "");

runs(function() {
myApi.get(function(error, success) {
// this never gets triggered as 401 are intercepted
});
setTimeout(function() {
flag = true;
}, 1000);
});

waitsFor(function() {
return flag;
}, "should be completed", 1200);

runs(function() {
expect(listener).toHaveBeenCalled();
});
});