title: How do I clear jest state (spies, mocks) between each test?
body: <p>I'm having an issue where jest is not clearing state between tests. I tried calling <code>restoreAllMocks()</code> in a <code>beforeEach()</code> and in an <code>afterEach()</code> and this didn't clear my <code>jest.spyOn(x, 'y').mockImplementation()</code> stub. I also tried <code>clearAllMocks()</code> and <code>resetAllMocks()</code>, no luck.</p>
  
  <p>My spec module:</p>
  
  <pre><code>function mockFeatureFlag(flagToMock: Flag) {
    jest.spyOn(FeatureFlags, 'singleton').mockImplementation(
      () =&gt;
        ({
          getFeatureFlag: (flag: Flag) =&gt;
            new Promise(resolve =&gt; {
              if (flag === flagToMock) {
                resolve(true);
              } else {
                resolve(false);
              }
            }),
        } as any),
    );
  }
  
    describe('bufferMinutesForDistance', () =&gt; {
      it('for small distances uses min buffer of 3h', async () =&gt; {
        const minutes = await util.bufferMinutesForDistance(1);
        expect(minutes).toBe(3 * 60);
      });
  
      it('for small distances when HALF_GHOST_BUFFER flag is true uses min buffer of 3h', async () =&gt; {
        mockFeatureFlag(Flag.HALF_GHOST_BUFFER);
        const minutes = await util.bufferMinutesForDistance(1);
        expect(minutes).toBe(3 * 60);
      });
  
      it('for long distances uses 12h buffer', async () =&gt; {
        const minutes = await util.bufferMinutesForDistance(1000);
        expect(minutes).toBe(12 * 60);
      });
  
      it('for long distances when HALF_GHOST_BUFFER flag is true cuts 12h buffer by half', async () =&gt; {
        mockFeatureFlag(Flag.HALF_GHOST_BUFFER);
        const minutes = await util.bufferMinutesForDistance(1000);
        expect(minutes).toBe(6 * 60);
      });
    });
  </code></pre>
  
  <p>There are 4 tests here. In tests 1 and 3, where I am not explicitly mocking the feature flag to return true, I expect it to return false (feature flags are false by default). Here, I call <code>mockImplementation</code> to make the feature flag return true in test 2. However, when running the tests, I see that the flag returns true in test 3 as well. I was not expecting this, since it means the spy state is leaking between tests.</p>
  
  <p>How do I prevent jest from leaking state between tests?</p>