LoginSignup
53
29

More than 5 years have passed since last update.

Typescriptでprivateメソッドをテストする

Posted at

Typescriptでprivateメソッドをテストしたかったが単純にメソッドにアクセスしようとすると怒られたので、
どうやったらテストできるか調べてみた。

How

以下の例で見ていく。

hoge.ts
export default class Hoge {
  private add(a: number, b: number) number {
    return a + b
  }
}
hoge.spec.ts
import Hoge from './hoge'

it("returns the addition of two numbers", () => {
  const hoge = new Hoge()
  expect(hoge.add(1, 2)).toBe(3)
})

テストを実行すると、

src/hoge.spec.ts (5,15): Property 'add' is private and only accessible within class 'Hoge'.

と怒られる。

解決方法は2つあって、

  1. anyにキャストして.hogeでアクセスする
   (hoge as any).add(1, 2)
  1. プライベートなメソッドに["hoge"]でアクセスする
   hoge["add"](1,2)
53
29
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
53
29