title: Jest: restore original module implementation on a manual mock
body: <p>I have a pretty common testing use case and I am not sure what's the best approach there.</p>
  
  <h2>Context</h2>
  
  <p>I would like to <strong>test a module that depends on a userland dependency</strong>. The userland dependency (<code>neat-csv</code>) <strong>exports a single function that returns a Promise</strong>.</p>
  
  <h2>Goal</h2>
  
  <p>I want to mock <code>neat-csv</code>'s behavior <strong>so that it rejects with an error for one single test. Then I want to restore the original module implementation.</strong></p>
  
  <p>AFAIK, I can't use <code>jest.spyOn</code> here as the module exports a single function.</p>
  
  <p>So I thought using manual mocks was appropriated and it works. However I can't figure it out how to restore the original implementation over a manual mock.</p>
  
  <h2>Simplified example</h2>
  
  <p>For simplicity here's a stripped down version of the module I am trying to test:</p>
  
  <pre><code>'use strict';
  
  const neatCsv = require('neat-csv');
  
  async function convertCsvToJson(apiResponse) {
    try {
      const result = await neatCsv(apiResponse.body, {
        separator: ';'
      });
      return result;
    } catch (parseError) {
      throw parseError;
    }
  }
  
  module.exports = {
    convertCsvToJson
  };
  </code></pre>
  
  <p>And here's an attempt of testing that fails on the second test (non mocked version):</p>
  
  <pre><code>'use strict';
  
  let neatCsv = require('neat-csv');
  let { convertCsvToJson } = require('./module-under-test.js');
  
  jest.mock('neat-csv', () =&gt;
    jest.fn().mockRejectedValueOnce(new Error('Error while parsing'))
  );
  
  const csv = 'type;part\nunicorn;horn\nrainbow;pink';
  const apiResponse = {
    body: csv
  };
  
  const rejectionOf = (promise) =&gt;
    promise.then(
      (value) =&gt; {
        throw value;
      },
      (reason) =&gt; reason
    );
  
  test('mocked version', async () =&gt; {
    const e = await rejectionOf(convertCsvToJson(apiResponse));
    expect(neatCsv).toHaveBeenCalledTimes(1);
    expect(e.message).toEqual('Error while parsing');
  });
  
  test('non mocked version', async () =&gt; {
    jest.resetModules();
    neatCsv = require('neat-csv');
    ({ convertCsvToJson } = require('./module-under-test.js'));
  
    const result = await convertCsvToJson(apiResponse);
    expect(JSON.stringify(result)).toEqual(
      '[{"type":"unicorn","part":"horn"},{"type":"rainbow","part":"pink"}]'
    );
  });
  </code></pre>
  
  <p>I am wondering if jest is designed to do such things or if I am going the wrong way and should inject neat-csv instead ? </p>
  
  <p>What would be the idiomatic way of handling this ?</p>