concept snapshot in category javascript
appears as: snapshots, snapshot

This is an excerpt from Manning's book Testing JavaScript Applications.
Listing 6.66. testUtils.js
// ... const detachPopstateHandlers = () => { const popstateListeners = window.addEventListener.mock.calls #1 .filter(([eventName]) => { return eventName === "popstate"; }); popstateListeners.forEach(([eventName, handlerFn]) => { #2 window.removeEventListener(eventName, handlerFn); }); jest.restoreAllMocks(); } module.exports = { clearHistoryHook, detachPopstateHandlers };Now, you can use
detachPopstateHandlersindomController.test.jsinstead of writing an inline function.
Tip
Interceptors get removed once they’re reached. To avoid tests failing because
fetchcan’t get a response, you must either create a new interceptor before each test or use nock’spersistmethod, as we’ve seen in chapter four.For this feature to be complete, your front-end must ask the server for the inventory items when it loads. After this change, it should only load the data in
localStorageif it can’t reach the server.Listing 6.74. main.js
// ... const { API_ADDR, data } = require("./inventoryController"); // ... const loadInitialData = async () => { try { const inventoryResponse = await fetch(`${API_ADDR}/inventory`); if (inventoryResponse.status === 500) throw new Error(); data.inventory = await inventoryResponse.json(); return updateItemList(data.inventory); #1 } catch (e) { const storedInventory = JSON.parse( #2 localStorage.getItem("inventory") ); if (storedInventory) { data.inventory = storedInventory; updateItemList(data.inventory); } } }; module.exports = loadInitialData();