0
0

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 1 year has passed since last update.

[Jest][備忘録] mockFn.mockImplementation(fn)に引数を渡さなかったら?

Last updated at Posted at 2023-02-09

TL;DR

undefinedが返る

試してみたコード

環境は

    "jest": "^28.1.3",
    "ts-jest": "^28.0.8",
    "typescript": "^4.9.3",

1~3はオマケ

sample.spec.ts
const obj = {
  sampleAdd: function (num: number) {
    return num + 10;
  },
};

beforeEach(() => {
  jest.clearAllMocks();
  jest.resetAllMocks();
  jest.restoreAllMocks();
});

it('1', () => {
  expect(obj.sampleAdd(10)).toBe(20);
});

it('2', () => {
  const spy = jest.spyOn(obj, 'sampleAdd');
  expect(obj.sampleAdd(2)).toBe(12);
  expect(spy).toHaveBeenCalledTimes(1);
});

it('3', () => {
  const spy = jest.spyOn(obj, 'sampleAdd').mockImplementation((num: number) => {
    return num + 100;
  });
  expect(obj.sampleAdd(2)).toBe(102);
  expect(spy).toHaveBeenCalledTimes(1);
});

it('4', () => {
  const spy = jest.spyOn(obj, 'sampleAdd').mockImplementation();
  expect(obj.sampleAdd(2)).toBeUndefined(); // undefinedを期待してPASSする
  expect(spy).toHaveBeenCalledTimes(1);
});

参照

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?