Angular10:噶茉莉窥探法

Angular 10: Karma Jasmine spied method

有什么方法可以在像这样侦测时重置侦测方法:

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

可以先把原来的方法存起来,等测试用例结束后再重新设置。

例如

  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方法。

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