🌊

[Jest]LocalStorageを型安全にモックする[TypeScript]

2022/06/09に公開

LocalStorageを型安全にモックする

自身の備忘録ですので結果のみ残します!
WindowLocalStorage型や、jest.spyOnの型情報をテキストエディターで追うと詳細が分かります

__mocks__/localStorage.ts
const mockLocalStorage = jest.spyOn<WindowLocalStorage, "localStorage">(
  window,
  "localStorage",
  "get"
);

let mockStorage: Record<string, string>;
const mockSetItem = jest.fn((key: string, value: string) => {
  mockStorage[key] = value;
});

const mockGetItem = jest.fn((key: string) => {
  return mockStorage[key];
});

const mockRemoveItem = jest.fn((key: string) => {
  delete mockStorage[key];
});

const originalLocalStorage = { ...window.localStorage } as const;

mockLocalStorage.mockImplementation(() => ({
  ...originalLocalStorage,
  getItem: mockGetItem,
  setItem: mockSetItem,
  removeItem: mockRemoveItem,
}));

export { mockLocalStorage };

getItem、setItemのような個別にモックではなく、localStorageをまとめてやっつけたかったのでメモ

GitHubで編集を提案

Discussion