Jest spyOn 不适用于从另一个文件导入函数的 React 功能组件 功能测试覆盖率报告错误

问题描述

我的 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,mockSet,mockSet);

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

覆盖率报告

coverage report

从第 197 行可以看出,它显然被调用了一次。

错误

Error snapshot

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

如果有帮助,我的存储库是开源的:https://github.com/lbragile/TabMerger,但此最新测试尚未包含在内。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)