最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock `angular.element` - Stack Overflow

programmeradmin1浏览0评论

In a service I have the following code snippet

angular.element('html, body').animate({
        scrollTop: this.parentHeight + ... - ...
    }, 500);

In my unit test I want to check if the correct values are given to the animate function. But how can I mock or spy this animate function ? I can think of something like this:

beforeEach(() => {
    angular.element = () => {
        return { animate: (options) => { .. }
    }
});

or better (but not working)

  spyOn(angular.element('html, body'), 'animate');

Is there a better (angular) way to do this ?

In a service I have the following code snippet

angular.element('html, body').animate({
        scrollTop: this.parentHeight + ... - ...
    }, 500);

In my unit test I want to check if the correct values are given to the animate function. But how can I mock or spy this animate function ? I can think of something like this:

beforeEach(() => {
    angular.element = () => {
        return { animate: (options) => { .. }
    }
});

or better (but not working)

  spyOn(angular.element('html, body'), 'animate');

Is there a better (angular) way to do this ?

Share Improve this question edited Oct 25, 2017 at 15:50 Vadim Kotov 8,2848 gold badges50 silver badges63 bronze badges asked Oct 15, 2015 at 14:48 Jeanluca ScaljeriJeanluca Scaljeri 29.3k66 gold badges235 silver badges382 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Something like this maybe?

var element = {
  animate: null,
  parentHeight: 100
};
spyOn(angular, 'element').andReturn(element);
spyOn(element, 'animate');

// Your test code goes here

expect(angular.element).toHaveBeenCalledWith('html, body');
expect(element.animate).toHaveBeenCalledWith(jasmine.objectContaining({
      scrollTop: 100
    }, 500);

发布评论

评论列表(0)

  1. 暂无评论