0

我的jest.Spyon实现看起来很简单,但是即使我看到它必须被调用,间谍函数“没有”被调用。

功能

/**
 * Initialize the local & sync storage when the user first installs TabMerger.
 * @param {{blacklist: string, color: string, dark: boolean,
 *  open: "with" | "without", restore: "keep" | "remove", title: string}} default_settings TabMerger's original default settings
 * @param {{color: string, created: string, tabs: object[], title: string}} default_group TabMerger's original default group (with up-to-date timestamp)
 * @param {HTMLElement} sync_node Node indicating the "Last Sync" time
 * @param {Function} setGroups For re-rendering the initial groups
 * @param {Function} setTabTotal For re-rendering the total tab counter
 *
 * @see defaultSettings in App.js
 * @see defaultGroup in App.js
 */
// prettier-ignore
export function storageInit(default_settings, default_group, sync_node, setGroups, setTabTotal) {
  chrome.storage.sync.get(null, (sync) => {
    if (!sync.settings) {
      chrome.storage.sync.set({ settings: default_settings }, () => {});
      toggleDarkMode(true);
    } else {
      toggleDarkMode(sync.settings.dark);
    }
 
    if (sync["group-0"]) {
      toggleSyncTimestampHelper(true, sync_node);
    }
 
    delete sync.settings;
    chrome.storage.local.get("groups", (local) => {
      var ls_entry = local.groups || { "group-0": default_group };
 
      chrome.storage.local.remove(["groups"], () => {
        chrome.storage.local.set({ groups: ls_entry }, () => {
          setGroups(JSON.stringify(ls_entry));
          updateTabTotal(ls_entry, setTabTotal);
        });
      });
    });
  });
}

测试

import * as AppFunc from "../src/App/App_functions";

/* 
{
  AppFunc:
  {
    toggleDarkMode: [Function: toggleDarkMode],
    ...
    toggleSyncTimestampHelper: [Function: toggleSyncTimestampHelper],
    storageInit: [Function: storageInit],
    ...
  }
}
*/

...

test("sync group-0 exists", () => {
  const spy = jest.spyOn(AppFunc, "toggleSyncTimestampHelper");
  sessionStorage.setItem("group-0", 1);

  // prettier-ignore
  AppFunc.storageInit(default_settings, default_group, sync_node, mockSet, mockSet);

  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy).toHaveBeenCalledWith(true, sync_node);
});

覆盖报告

覆盖率报告 从第 197 行可以看出,它显然被调用了一次。

错误

错误快照

这非常令人困惑,因为我的测试成功chrome.storage.___.___使用了 spyOn API,jest.spyOn(chrome.storage.local, "get")但这失败了。

如果有帮助,我的存储库是开源的:https ://github.com/lbragile/TabMerger ,但是这个最新的测试还没有包含在其中。

4

0 回答 0