简体   繁体   中英

Jasmine: testing function with promise

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);
        });
    });
});

It looks like your test needs 2 digest cycles. httpBackend.flush for simulating server response and scope.$apply for resolving the promise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM