Mock Dependencies Manually

HyperTest provides a way for you to manually mock certain dependencies that are not instrumented automatically.

Please check the list of automatically instrumented packages, before proceeding with manual mocks.

These mocks also come in handy when you want to reduce false positives in the test reports caused by a utility that returns arbitrary values e.g., timestamps, and UUIDs.

Let's look at an example where manual mocks can be utilized.

Below is an API route that generates PROMO code for a user.

function generatePromoCode(userId) {
  // Generate a unique promo code based on userId or any other logic
  const uniquePart = uuidv4().split('-')[0]; // Take the first part of a UUID
  return `PROMO-${uniquePart}-${userId}`;
}

app.post('/generate_promo_code', (req, res) => {
  const { emailId } = req.body;
  const userInst = db.User.findOne({ where: { emailId } });
  
  const promoCode = generatePromoCode(userInst.id);
  res.json({ promoCode });
});

If we record this API interaction and run a Test then HyperTest will report a value-modified error, but this is a false positive and it's not a real change that was made in the logic.

To eliminate this recurrent issue we can manually mock the generation of the Promo code. When we re-record this API interaction we will also have the exact value of the Promo code that was generated and the same will be used in the Test.

const { createManualMock } = require('@hypertestco/node-sdk');

app.post('/generate_promo_code', (req, res) => {
  const { emailId } = req.body;
  const userInst = db.User.findOne({ where: { emailId } });
  
  const promoCode = createManualMock({
    uniqueIdentifier: 'generatePromoCode',
    defaultValue: 'PROMO-DEFAULT-123',
    execFn() {
      return generatePromoCode(userInst.id);
    },
  });

  res.json({ promoCode });
});

function generatePromoCode(userId) {
  // Generate a unique promo code based on user_id or any other logic
  const uniquePart = uuidv4().split('-')[0]; // Take the first part of a UUID
  return `PROMO-${uniquePart}-${userId}`;
}

To create a manual mock you need to give these input params:

  • uniqueIdentifier: An identifier is needed to pick the right mock during REPLAY, if you are making the same kind of function calls then consider adding a number to the identifier.

  • defaultValue: A default value is required for a case where we are unable to find the recorded mock, e.g., you changed the identifier value or added a new manual mock and if we run an old recorded test that has different mocks then this default value will be used.

  • execFn: This is a wrapper function that contains the logic you want to mock manually, in RECORD mode the return value of this function will be kept to use in the REPLAY mode(Test).

If we run a test with the manual mock in place it passes.

Last updated