46
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Jest mockClear(), mockReset(), mockRestore() の違い

Last updated at Posted at 2021-03-29

Jest の mockClear(), mockReset(), mockRestore() の違いが分かりづらいのでまとめておく。
また jest.clearAllMocks(), jest.resetAllMocks(), jest.restoreAllMocks() もすべてのモックが対象になるだけで挙動としては同じ。

mockClear()

mockFn.mock.calls, mockFn.mock.instances を初期化する。

const now = () => Date.now();

describe('mock example', () => {
  const mockedDateNow = jest.spyOn(Date, 'now').mockReturnValue(0);

  it('mockClear', () => {
    now();
    mockedDateNow.mockClear();
    // calls, instances はすべて初期化されている
    expect(mockedDateNow.mock.calls.length).toBe(0);
    expect(mockedDateNow.mock.instances.length).toBe(0);
    // mockReturnValue の設定は初期化されていない
    expect(now()).toBe(0);
  });
});

mockReset()

mockFn.mock, mockFn.mock.calls, mockFn.mock.instances を初期化する。
また mockImplementation, mockReturnValue 等で設定した実装、戻り値もすべてリセットされる。

const now = () => Date.now();

describe('mock example', () => {
  const mockedDateNow = jest.spyOn(Date, 'now').mockReturnValue(0);

  it('mockReset', () => {
    now();
    mockedDateNow.mockReset();
    // calls, instances はすべて初期化されている
    expect(mockedDateNow.mock.calls.length).toBe(0);
    expect(mockedDateNow.mock.instances.length).toBe(0);
    // mockReturnValue の設定も初期化されている
    expect(now()).not.toBe(0);
  });
});

mockRestore()

jest.spyOn によって作成されたモックをオリジナルのものへ戻す。

const now = () => Date.now();

describe('mock example', () => {
  const mockedDateNow = jest.spyOn(Date, 'now').mockReturnValue(0);

  it('mockRestore', () => {
    now();
    mockedDateNow.mockRestore();
    // mockRestore() により Date.now がモックでなくなっている
    expect((Date.now as any).mock).toBe(undefined);
  });
});
46
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?