返回課程

間諜裝飾器

重要性:5

建立一個裝飾器 spy(func),它會傳回一個包裝函式,將所有呼叫函式的內容儲存在其 calls 屬性中。

每個呼叫都儲存為一個陣列,內容為參數。

例如

function work(a, b) {
  alert( a + b ); // work is an arbitrary function or method
}

work = spy(work);

work(1, 2); // 3
work(4, 5); // 9

for (let args of work.calls) {
  alert( 'call:' + args.join() ); // "call:1,2", "call:4,5"
}

P.S. 該裝飾器有時對單元測試很有用。它的進階形式是 Sinon.JS 函式庫中的 sinon.spy

在沙盒中開啟測試。

spy(f) 回傳的包裝函式應儲存所有參數,然後使用 f.apply 轉發呼叫。

function spy(func) {

  function wrapper(...args) {
    // using ...args instead of arguments to store "real" array in wrapper.calls
    wrapper.calls.push(args);
    return func.apply(this, args);
  }

  wrapper.calls = [];

  return wrapper;
}

在沙盒中開啟測試的解決方案。