All Projects → clarkbw → Jest Localstorage Mock

clarkbw / Jest Localstorage Mock

Licence: bsd-3-clause
A module to mock window.localStorage and window.sessionStorage in Jest

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Jest Localstorage Mock

Nuxt Storage
🛢 Utilities for easy read and write browser's storage in Nuxt.js project
Stars: ✭ 98 (-60.32%)
Mutual labels:  localstorage, sessionstorage
Ngx Store
Angular decorators to automagically keep variables in HTML5 LocalStorage, SessionStorage, cookies; injectable services for managing and listening to data changes and a bit more.
Stars: ✭ 152 (-38.46%)
Mutual labels:  localstorage, sessionstorage
React Nativeish
React Native / React Native Web Boilerplate
Stars: ✭ 106 (-57.09%)
Mutual labels:  jest, mock
Recoil Persist
Package for recoil state manager to persist and rehydrate store
Stars: ✭ 66 (-73.28%)
Mutual labels:  localstorage, sessionstorage
Sinon Jest Cheatsheet
Some examples on how to achieve the same goal with either of both libraries: sinon and jest. Also some of those goals achievable only by one of these tools.
Stars: ✭ 226 (-8.5%)
Mutual labels:  jest, mock
Bin
A tiny (<1kb) localStorage and sessionStorage helper library.
Stars: ✭ 70 (-71.66%)
Mutual labels:  localstorage, sessionstorage
React Storage Hooks
React hooks for persistent state
Stars: ✭ 146 (-40.89%)
Mutual labels:  localstorage, sessionstorage
Web Storage Cache
对localStorage 和sessionStorage 进行了扩展,添加了超时时间,序列化方法
Stars: ✭ 582 (+135.63%)
Mutual labels:  localstorage, sessionstorage
Brownies
🍫 Tastier cookies, local, session, and db storage in a tiny package. Includes subscribe() events for changes.
Stars: ✭ 2,386 (+865.99%)
Mutual labels:  localstorage, sessionstorage
Jest Canvas Mock
🌗 A module used to mock canvas in Jest.
Stars: ✭ 189 (-23.48%)
Mutual labels:  jest, mock
Graphql Query Test Mock
Easily mock GraphQL queries in your Relay Modern / Apollo / any-other-GraphQL-client tests.
Stars: ✭ 49 (-80.16%)
Mutual labels:  jest, mock
Awesome Web Storage
😎 Everything you need to know about Client-side Storage.
Stars: ✭ 227 (-8.1%)
Mutual labels:  localstorage, sessionstorage
Proxy Storage
Provides an adapter for storage mechanisms (cookies, localStorage, sessionStorage, memoryStorage) and implements the Web Storage interface
Stars: ✭ 10 (-95.95%)
Mutual labels:  localstorage, sessionstorage
Vue Mail List
vue全家桶+localStorage实现一个简易的通讯录
Stars: ✭ 81 (-67.21%)
Mutual labels:  localstorage, sessionstorage
Storagedb
MongoDB-like API for HTML5 Storage (localStorage and sessionStorage)
Stars: ✭ 16 (-93.52%)
Mutual labels:  localstorage, sessionstorage
Store
A better way to use localStorage and sessionStorage
Stars: ✭ 1,646 (+566.4%)
Mutual labels:  localstorage, sessionstorage
Ng2 Webstorage
Localstorage and sessionstorage manager - Angular service
Stars: ✭ 395 (+59.92%)
Mutual labels:  localstorage, sessionstorage
Vue Ls
💥 Vue plugin for work with local storage, session storage and memory storage from Vue context
Stars: ✭ 468 (+89.47%)
Mutual labels:  localstorage, sessionstorage
React Local Storage
Showcase on how to use the native localStorage of the browser in React.
Stars: ✭ 168 (-31.98%)
Mutual labels:  localstorage, sessionstorage
Jest Mock Extended
Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
Stars: ✭ 224 (-9.31%)
Mutual labels:  jest, mock

Use this module with Jest to run web tests that rely on localstorage and / or sessionStorage where you want a working localStorage API with mocked functions.

This module has no runtime dependencies so your project won't pull in additional module dependencies by using this.

npm npm Codecov Greenkeeper badge Twitter

Jest 24+

Note that with [email protected] and above this project potentially duplicating functionality.

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing. The module is transpiled via babel to support the current active Node LTS version (6.11.3).

yarn:

yarn add --dev jest-localstorage-mock

npm:

npm i --save-dev jest-localstorage-mock

Setup

The simplest setup is to use the module system, you may also choose to create a setup file if needed.

Module

In your package.json under the jest configuration section create a setupFiles array and add jest-localstorage-mock to the array. Also, ensure you have not enabled resetMocks.

{
  "jest": {
    "resetMocks": false,
    "setupFiles": ["jest-localstorage-mock"]
  }
}

If you already have a setupFiles attribute you can also append jest-localstorage-mock to the array.

{
  "jest": {
    "resetMocks": false,
    "setupFiles": ["./__setups__/other.js", "jest-localstorage-mock"]
  }
}

Setup file

Alternatively you can create a new setup file which then requires this module or add the require statement to an existing setup file.

__setups__/localstorage.js

import 'jest-localstorage-mock';
// or
require('jest-localstorage-mock');

Add that file to your setupFiles array:

"jest": {
  "setupFiles": [
    "./__setups__/localstorage.js"
  ]
}

In create-react-app

For a create-react-app project you can replace the suggested mock with this at the beginning of the existing src/setupTests.js file:

require('jest-localstorage-mock');

You must also override some of create-react-app's default jest configuration. You can do so in your package.json:

{
  "jest": {
    "resetMocks": false
  }
}

For more information, see #125.

In tests

By including this in your Jest setup you'll allow tests that expect a localStorage and sessionStorage object to continue to run. The module can also allow you to use the mocks provided to check that your localStorage is being used as expected.

The __STORE__ attribute of localStorage.__STORE__ or sessionStorage.__STORE__ is made available for you to directly access the storage object if needed.

Test Examples

Check that your localStorage calls were made when they were supposed to.

test('should save to localStorage', () => {
  const KEY = 'foo',
    VALUE = 'bar';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
  expect(localStorage.__STORE__[KEY]).toBe(VALUE);
  expect(Object.keys(localStorage.__STORE__).length).toBe(1);
});

Check that your sessionStorage is empty, examples work with either localStorage or sessionStorage.

test('should have cleared the sessionStorage', () => {
  dispatch(action.reset());
  expect(sessionStorage.clear).toHaveBeenCalledTimes(1);
  expect(sessionStorage.__STORE__).toEqual({}); // check store values
  expect(sessionStorage.length).toBe(0); // or check length
});

Check that localStorage calls were not made when they shouldn't have been.

test('should not have saved to localStorage', () => {
  const KEY = 'foo',
    VALUE = 'bar';
  dispatch(action.notIdempotent(KEY, VALUE));
  expect(localStorage.setItem).not.toHaveBeenLastCalledWith(KEY, VALUE);
  expect(Object.keys(localStorage.__STORE__).length).toBe(0);
});

Reset your localStorage data and mocks before each test to prevent leaking.

beforeEach(() => {
  // to fully reset the state between tests, clear the storage
  localStorage.clear();
  // and reset all mocks
  jest.clearAllMocks();
  
  // clearAllMocks will impact your other mocks too, so you can optionally reset individual mocks instead:
  localStorage.setItem.mockClear();
  // you can also directly reset the storage (same as .clear above)
  localStorage.__STORE__ = {};
});

test('should not impact the next test', () => {
  const KEY = 'foo',
    VALUE = 'bar';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
  expect(localStorage.__STORE__[KEY]).toBe(VALUE);
  expect(Object.keys(localStorage.__STORE__).length).toBe(1);
});

test('should not be impacted by the previous test', () => {
  const KEY = 'baz',
    VALUE = 'zab';
  dispatch(action.update(KEY, VALUE));
  expect(localStorage.setItem).toHaveBeenLastCalledWith(KEY, VALUE);
  expect(localStorage.__STORE__[KEY]).toBe(VALUE);
  expect(Object.keys(localStorage.__STORE__).length).toBe(1);
});

See the contributing guide for details on how you can contribute.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].