【问题标题】:Angular 10: Karma Jasmine spied methodAngular 10:Karma Jasmine 间谍方法
【发布时间】:2020-12-08 13:05:25
【问题描述】:

有什么方法可以在像这样被窥探时重置被窥探的方法:

it('unit test', () => {
    document.getElementById = jasmine.createSpy().and.returnValue(document.createElement('div'));
    ....
})

【问题讨论】:

    标签: angular unit-testing dom jasmine karma-jasmine


    【解决方案1】:

    您可以在开始时存储原始方法,然后在测试用例完成后将其重置。

    例如

      it('unit test', () => {
        const getElementById = document.getElementById;
        document.getElementById = jasmine
          .createSpy()
          .and.returnValue(document.createElement('div'));
        console.log(document.getElementById);
        document.getElementById = getElementById;
        console.log(document.getElementById);
      });
    

    日志:

    LOG: function wrap() { ... }
    Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 14 SUCCESS (0 secs / 0.023 secs)
    LOG: function getElementById() { ... }
    Chrome 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 14 SUCCESS (0 secs / 0.023 secs)
    

    第一个日志打印由间谍包裹的getElementById 方法。

    第二个日志打印原始版本。

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 2023-03-20
      • 2017-09-26
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 2019-02-05
      • 2023-04-01
      • 2015-12-07
      相关资源
      最近更新 更多