You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Node.js环境中Mock chrome.storage(local/session)API用于测试?

在Node.js中Mock chrome.storage(local/session)API的内存实现

你可以手动实现一个基于内存的Mock,完全复刻chrome.storage的API行为,确保调用set后能通过get获取到对应值,同时兼容Chrome扩展API的回调模式。

实现代码

创建一个mock-chrome-storage.js文件,内容如下:

const createStorageArea = () => {
  const storage = {};

  return {
    set(items, callback) {
      Object.assign(storage, items);
      typeof callback === 'function' && callback();
    },
    get(keys, callback) {
      let result = {};
      if (typeof keys === 'string') {
        result[keys] = storage[keys];
      } else if (Array.isArray(keys)) {
        keys.forEach(key => {
          if (storage.hasOwnProperty(key)) {
            result[key] = storage[key];
          }
        });
      } else if (typeof keys === 'object') {
        result = {...keys};
        Object.keys(storage).forEach(key => {
          if (result.hasOwnProperty(key)) {
            result[key] = storage[key];
          }
        });
      } else {
        result = {...storage};
      }
      typeof callback === 'function' && callback(result);
    },
    remove(keys, callback) {
      const keysToRemove = Array.isArray(keys) ? keys : [keys];
      keysToRemove.forEach(key => delete storage[key]);
      typeof callback === 'function' && callback();
    },
    clear(callback) {
      Object.keys(storage).forEach(key => delete storage[key]);
      typeof callback === 'function' && callback();
    }
  };
};

// 全局挂载chrome对象,供测试代码调用
global.chrome = {
  storage: {
    local: createStorageArea(),
    session: createStorageArea()
  }
};

使用示例

在测试文件中先引入这个Mock,之后就可以像使用真实的chrome.storage一样编写测试用例(以Jest为例):

require('./mock-chrome-storage');

test('chrome.storage.local 能正常存取值', done => {
  chrome.storage.local.set({username: 'alice', score: 95}, () => {
    chrome.storage.local.get(['username', 'score'], result => {
      expect(result).toEqual({username: 'alice', score: 95});
      done();
    });
  });
});

test('chrome.storage.session 支持清除所有存储', done => {
  chrome.storage.session.set({token: 'xyz789'}, () => {
    chrome.storage.session.clear(() => {
      chrome.storage.session.get('token', result => {
        expect(result.token).toBeUndefined();
        done();
      });
    });
  });
});

扩展优化(可选)

如果需要支持Promise链式调用(比如chrome.storage.local.set(...).then(...)),可以给每个方法添加Promise返回:

// 修改createStorageArea中的set方法为例
set(items, callback) {
  Object.assign(storage, items);
  typeof callback === 'function' && callback();
  return Promise.resolve();
}

其他方法(get/remove/clear)同理修改即可,这样就能同时兼容回调和Promise两种调用方式。

内容的提问来源于stack exchange,提问作者4ntoine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:31:32