IceManSpy
IceManSpy

Reputation: 1098

Jest mocks - how to restore original function between tests

I have my function:

report.js:

const ctrl = {};
const _ = require('lodash');
const boom = require("boom");
const slackNotifications = require('./../../slack/controllers/notifications');
const reportModel = require("./../models/report");

import validationSchema from "./../_validation/report";

ctrl.addReport = async (req, res) => {
  const { body } = req;

  try {
    const validatedData = await validationSchema.validate(body);
    const report = await reportModel(req.dbConnection).addReport(validatedData);

    if (report.reported) {
      await slackNotifications.notify('Notify me!');
      res.status(200).send({ reported: true });
    } else {
      throw boom.serverUnavailable("Can't offer report");
    }
  } catch (err) {
    throw boom.badRequest(err);
  }
};

module.exports = ctrl;

The validation schema is schema created by using yup.js.

Here are the tests

The problem is throw Error when validation failed test. I've got

TypeError: Cannot read property 'output' of undefined

from 109 line

const { output, output: { payload } } = err;.

But my expected value is error threw by validationSchema.validate and caught in 23rd line of my function.

When I run only this test everything is ok. I've got the correct error with status code and message.

How can I restore the original function validationSchema.validate from this test (84th line)?

I've tried to restore by:

jest.mock('./../_validation/report', () => ({
  // validate: jest.fn().mockReset(),
  validate: jest.fn().mockClear(),
}));

But I'm not sure that is the correct way.

Upvotes: 1

Views: 1780

Answers (1)

Julien TASSIN
Julien TASSIN

Reputation: 5212

You can use requireActual in your test to execute the original behaviour for just one test.

This way :

jest.mock('./../_validation/report', () => ({
  validate: jest.requireActual('./../_validation/report').validate,
}));

This way, the real validate will be called Of course, at the next test (or in a beforeEach), you can re-mock your function.

Upvotes: 2

Related Questions