Reputation: 1035
I've just started creating unit tests using Jasmine and Karma for my angular app. I have a test that is failing when I think it shouldn't be. I want to get the console output from the controller itself, not just the jasmine tests that run on the controller, is this possible?
Here is a code example: the test:
it('First test', function() {
var ctrl = controller('controller', {$scope: scope, MyHttpService: MyHttpMock});
scope.update();
console.log("I can see this console output");
expect(scope.campaignID).toEqual('');
expect(scope.data.pending).toEqual(20); // <--- fails here
});
the controller:
$scope.update = function() {
MyHttpService.get('stats').then(function(data) {
console.log("the data: ", data); // <-- can't see this output
$scope.data = data;
});
}
--EDIT--
Here is the code for MyHttpMock:
var MyHttpMock = {
get: function(key) {
var deferred = $q.defer(),
promise = deferred.promise;
promise.then(function(data) {
return data;
});
if (key == "stats") {
deferred.resolve({"pending": 20})
} else {
deferred.resolve({});
}
return promise;
}
};
I originally didn't include it because my question is about how to see the debug output from within the controller, not debugging this specific problem. But here it is anyway just in case it helps.
--END EDIT--
I can see in the console log from the test that the return value looks correct. The mock service seems to be doing what it is supposed to do. But the test is failing, and it shows scope.pending as undefined. MyHttpService
returns a promise, and I have a suspicion that it is not structured correctly, or something like that. However, I'm not sure how to inspect it.
Is there a way to view the console log from within the controller to see what data is actually getting passed in?
Upvotes: 1
Views: 1399
Reputation: 18387
Your promise.then() is pointless since it's just wrapping the original promise with the same trivial return value. You should remove that line. As it stands, .then() returns a different, new derived promise, but you're returning the original non-derived.
Upvotes: 0
Reputation: 123739
Assuming your mock returns a promise, something like the below one:-
var MyHttpMock = jasmine.createSpyObj('MyHttpMock', ['get']);
MyHttpMock.get.and.returnValue($q.when({pending:20}));
In your test before setting the expectation and after making the specific call you need to manually perform a digest cycle to resolve the promise.
it('First test', function() {
var ctrl = controller('controller', {$scope: scope, MyHttpService: MyHttpMock});
scope.update();
scope.$apply(); //Trigger a digest
///...
expect(scope.data.pending).toEqual(20);
});
Upvotes: 2