Test an asynchronous function not within a service

2019-08-16 14:58发布

问题:

If I have a directive that takes a function from the scope, and that function is asynchronous how could I test that? For example

angular.module('myApp').factory('AsyncService',() => {
    return {
        async: // function that returns a promise
    }
})

angular.module('myApp').directive('asyncDirective', () => ({
    scope: { async: = },
    link: scope => {
        scope.async.then(//do something)
    }
}));

angular.module('myApp').controller('ctrl', ($scope, AsyncService) => {
    $scope.asyncService = AysncService;
});

<async-directive async="asyncService.async" />

The above code is an example of how the directive might be used, but I only want to test the directive alone. Since the directive expects a function and not an object that it can use to call a function, how would I test it? If I used a spy, what would I spy on?

回答1:

The service should be stubbed:

beforeEach(() => {
  module('myApp', { AsyncService: { async: jasmine.createSpy() } });
})

Then the method can be mocked to return a promise before directive compilation:

AsyncService.async.and.returnValue($q.resolve(...));