【问题标题】:How can I test jquery call using jasmine?如何使用茉莉花测试 jquery 调用?
【发布时间】:2017-05-30 19:34:31
【问题描述】:

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

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

我如何用茉莉花测试这个?只是为了检查是否调用了“动画”方法。

【问题讨论】:

    标签: jquery angular unit-testing jasmine


    【解决方案1】:

    你需要使用几个函数...

    • 首先,为animate函数设置spy。可能您希望为所有测试或在每个测试之前执行此操作,可能只是针对一个测试;你可能还想在spy拦截呼叫后做,例如.and.callFake().and.callThrough()等...

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

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

    有关 Jasmine 测试的更多信息是 over here

    【讨论】:

    • 感谢您的回复。但不幸的是,它不起作用:errors + 我在 Visual Studio Code 中遇到下一个错误:“类型 'JQueryStatic' 上不存在属性 'animate'。”
    • @Maxim 抱歉,我修复了代码示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    相关资源
    最近更新 更多