如何使用Jasmine测试jQuery调用



我在Angular的组件中有下一个方法:

private onTopClick() {
  $('body,html').animate({ scrollTop: 0 });
}

如何用茉莉花测试?只是为了检查"动画"方法已被调用。

您需要使用几个功能...

  • 首先,为animate功能设置间谍。可能您想在所有测试中或在每次测试之前都这样做,这可能只是一个测试;间谍拦截呼叫后,您可能还想做,例如.and.callFake().and.callThrough()等...

    beforeEach(function() {
         spyOn($.fn, "animate");
    });
    
  • 在您的实际测试中,检查是否调用animate功能。可能看起来像...

     it("should call '$(selector).animate'", function () {
          onTopClick();
          expect($.fn.animate).toHaveBeenCalled();
     });
    

有关茉莉测试的更多信息在这里。

最新更新