LoginSignup
0
0

More than 1 year has passed since last update.

Node.jsの標準ライブラリのメソッドをJestでモックする方法

Posted at

先日NodeのテストコードをJestで書いていた際にMathやcrypto等の標準ライブラリのモックでドハマりしたので投稿
StackOverFlowとかを数時間彷徨った結果色々やり方ありそうだったけど、自分の環境だと結局このやり方しか動かなかったので参考までに

環境

  • Ubuntu20.04(WSL2)
  • Node: 18.12.0
  • Jest: 29.4.3
  • ts-node: 10.9.1
  • ts-jest: 29.0.5
  • TypeScript: 4.9.5

結論

モックしたいメソッド = jest.fn().mockReturnValue(返したい値)

単なる乱数を返すだけの関数ですが、以下のようにモックしてやるとテスト実行時に毎回異なる乱数を返すことがなくなります
TSなのでjest.fnに型引数を与えてますが、当然ながらJSなら無くていいです

index.ts
const getRandomNum = () => {
  return Math.random()
}

export default getRandomNum
index.spec.ts
import { jest, test, expect } from '@jest/globals'
import getRandomNum from "./index.js"

// この1行でモックしている
Math.random = jest.fn<() => number>().mockReturnValue(0.1111111111111111).
 
test("Math.randomの値がモックされている", () => {
  const result = getRandomNum()
  expect(result).toBe(0.1111111111111111)
})
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