2
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 3 years have passed since last update.

【Jest】console.log()をmock化する方法2通り

Last updated at Posted at 2021-04-29

jestでconsole.log()モック化する方法2通りと、それぞれconsole.log()が2回呼び出されたことをテストするためのマッチャーを記す。

方法1

// モック化
global.console.log= jest.fn();
// マッチャー
expect(global.console.log).toHaveBeenCalledTimes(2);

さらにglobal.は省略してもよさそう

// モック化
console.error = jest.fn();
// マッチャー
expect(console.log).toHaveBeenCalledTimes(2);

方法2

// モック化
const spyConsoleLog = jest.spyOn(global.console, "log").mockImplementation();
// マッチャー
expect(spyConsoleLog).toHaveBeenCalledTimes(2);
2
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
2
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?