Manage Global Variables

The kvStore utility within our Node.js SDK provides a key-value storage mechanism designed to capture and mock the state of global variables or objects accessed during API calls.

Why mock Global Variables?

In the development of unit tests, especially within environments where global variables or objects are accessed or modified, it is crucial to maintain a consistent state across tests to ensure their reliability and accuracy.

Changes to the global state can lead to unpredictable behavior in tests, potentially resulting in false positives or negatives. This is particularly true in scenarios where tests run in parallel.

The kvStore utility addresses this issue by allowing developers to capture and mock the state of global variables or objects.

By doing so, it ensures that each test runs in a controlled environment, with predefined states, making the tests deterministic and independent of external factors or changes in the global state.

How to use kvStore

The utility is straightforward to use, involving simple methods to set, get, and remove key-value pairs that represent the state of global variables or objects.

Consider a scenario where your e-commerce application uses a global configuration shouldReturnStockQuantity that dictates whether the platform displays the exact number of items left in stock (e.g., "Only 2 items left!") or a simple in-stock/out-of-stock message.

This mode affects how product APIs respond to queries on product details, influencing purchasing decisions.

import { kvStore } from "@hypertestco/node-sdk";

// let SHOULD_RETURN_STOCK_QUANTITY = true; // old global variable
async function updateStockQuantityConfig() {
  setInterval(async () => {
    const { data: { shouldReturnStockQuantity } } = await axios.get('http://host/getConfig');

    // SHOULD_RETURN_STOCK_QUANTITY = shouldReturnStockQuantity;
    kvStore.set('shouldReturnStockQuantity', shouldReturnStockQuantity === true);
  }, 5 * 1000); // Poll every 5 seconds


app.get('/getInventoryStats', (req, res) => {
  const inventoryStats = db.InventoryStats.find({
    select: {
      // stock: SHOULD_RETURN_STOCK_QUANTITY, // source of inconsistency
      stock: kvStore.get('shouldReturnStockQuantity'),

  res.json({ inventoryStats });

By using kvStore we ensure that the tests are immune to unpredictable behavior caused by external factors.

Last updated