title: How should I mock a specific function in a module?
body: <pre class="lang-js prettyprint-override"><code>function a() {
    return &quot;a&quot;;
  }
  
  function b() {
    return a();
  }
  
  export { a, b };
  </code></pre>
  <p>Let's say I have a utils.js like this, and I just want to mock <code>a()</code> function that is being used by <code>b()</code> function within the same file.</p>
  <p>After googling all around, I <a href="https://www.chakshunyu.com/blog/how-to-mock-only-one-function-from-a-module-in-jest/" rel="nofollow noreferrer">found an article</a> that seemed to be just for this case.</p>
  <pre class="lang-js prettyprint-override"><code>import {a, b} from &quot;./utils&quot;
  
  jest.mock(&quot;./utils&quot;, () =&gt; {
    const original = jest.requireActual(&quot;./utils&quot;);
    return {
      ...original,
      a: jest.fn().mockReturnValue(&quot;modified a&quot;)
    };
  });
  
  describe(&quot;utils&quot;, () =&gt; {
    it(&quot;sholuld use mocked a()&quot;, () =&gt; {
      expect(b()).toEqual(&quot;modified a&quot;)
      expect(a).toHaveBeenCalledTimes(1)
    });
  });
  </code></pre>
  <p>I did it like this, but it seems <code>b()</code> function is still calling the real <code>a()</code> function despite the fact that I am mocking <code>a()</code> function specifically.</p>
  <pre><code>
  Expected: &quot;modified a&quot;
  Received: &quot;a&quot;
  
    11 | describe(&quot;utils&quot;, () =&gt; {
    12 |   it(&quot;sholuld use mocked a()&quot;, () =&gt; {
  &gt; 13 |     expect(b()).toEqual(&quot;modified a&quot;)
        |                 ^
    14 |     expect(a).toHaveBeenCalledTimes(1)
    15 |   })
    16 | })
  
  </code></pre>
  <p>Is it even possible to mock a function for such this case?</p>