Reputation: 31580
I have a service that wraps ajax calls ($http) and returns a promise. In my controller, I resolve the promise with MyService.stuff(…).
then
(fn(data){ $scope.stuff = data; })
How do I test the value of $scope.stuff
?
// controller
$scope.stuff = false;
$scope.getStuff = function(name)
{
if ( !angular.isDefined( $scope.users[ name ] ) )
MyService.stuff( 'get' , username ).then(function(data)
{ // returns the value of resp.data
$scope.stuff = $scope.users[ name ] = data;
});
else
$scope.stuff = $scope.users[ name ];
};
What I've got for the test looks like this:
// test
describe('scope.stuff',function()
{
it('should initialize as false', function ()
{ // this passes
expect(scope.stuff).toBe(false);
});
var httpBackend;
beforeEach(inject(function($httpBackend){
httpBackend = $httpBackend;
}));
it('should have 4 elements', function()
{ // this stalls
runs(function()
{
httpBackend.whenGET().respond(200,
{ data: [
{name: 'foo'}, {name: 'bar'}, {name: 'baz'},{name: 'qux'}
]});
scope.getStuff('foo');
});
waitsFor(function()
{
scope.$apply();
return scope.stuff;
});
runs(function()
{
expect(scope.stuff.length).toBe(4);
});
});
});
Upvotes: 1
Views: 223
Reputation: 4345
It looks like your test needs 2 digest cycles. httpBackend.flush for simulating server response and scope.$apply for resolving the promise
Upvotes: 2