57
30

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 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)
    
  2. プライベートなメソッドに["hoge"]でアクセスする

    hoge["add"](1,2)
    
57
30
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
57
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?