Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
jest-localstorage-mock
Advanced tools
Auto mock all localstorage and sessionstorage APIs for your Jest tests
The jest-localstorage-mock package is a Jest mock for the localStorage API, allowing developers to test code that interacts with localStorage without relying on the actual browser implementation. This can help ensure tests are isolated and run consistently across different environments.
Mocking localStorage
This feature allows you to mock the localStorage API, enabling you to test interactions with localStorage without relying on the actual browser implementation. The code sample demonstrates how to set an item in localStorage and verify that it was set correctly.
const localStorageMock = require('jest-localstorage-mock');
// Example test
it('should store an item in localStorage', () => {
localStorage.setItem('key', 'value');
expect(localStorage.setItem).toHaveBeenCalledWith('key', 'value');
expect(localStorage.getItem('key')).toBe('value');
});
Clearing localStorage
This feature allows you to clear the localStorage, which is useful for ensuring a clean state between tests. The code sample demonstrates setting an item in localStorage and then clearing it, verifying that the item is no longer present.
const localStorageMock = require('jest-localstorage-mock');
// Example test
it('should clear localStorage', () => {
localStorage.setItem('key', 'value');
localStorage.clear();
expect(localStorage.getItem('key')).toBeNull();
});
Removing an item from localStorage
This feature allows you to remove a specific item from localStorage. The code sample demonstrates setting an item in localStorage, removing it, and verifying that it has been removed.
const localStorageMock = require('jest-localstorage-mock');
// Example test
it('should remove an item from localStorage', () => {
localStorage.setItem('key', 'value');
localStorage.removeItem('key');
expect(localStorage.getItem('key')).toBeNull();
});
localstorage-memory is an in-memory implementation of the localStorage API. It can be used in Node.js environments to simulate localStorage without relying on a browser. Compared to jest-localstorage-mock, localstorage-memory is more focused on providing a full in-memory localStorage implementation rather than just mocking it for tests.
node-localstorage is a package that provides a localStorage implementation for Node.js. It writes data to disk, making it persistent across sessions. This is different from jest-localstorage-mock, which is designed specifically for mocking localStorage in tests and does not provide persistence.
mock-local-storage is another package that mocks the localStorage and sessionStorage APIs for testing purposes. It is similar to jest-localstorage-mock but also includes support for sessionStorage, providing a more comprehensive solution for testing storage APIs.
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.
Note that with jest@24
and above this project potentially duplicating functionality.
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
The simplest setup is to use the module system, you may also choose to create a setup file if needed.
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"]
}
}
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"
]
}
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.
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.
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();
});
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.
FAQs
Auto mock all localstorage and sessionstorage APIs for your Jest tests
We found that jest-localstorage-mock demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.