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

[Jest] DIしたオブジェクトのメソッド呼び出しをテストする

Posted at

こんにちは、スープです。
医療テックのスタートアップのお手伝いをしています。

DIしたオブジェクトのメソッド呼び出し方法を調べました。
わかりやすくするために、シンプルな例を示します。

export class CarFactory {
  constructor(private logger: ILogger) {}

  public create(name: string): void {
    this.logger.log(`creating ${name} car...`)
  }
}

このとき、コンストラクターインジェクションされた loggerlog が呼ばれていることをテストしてみます。

describe('CarFactory', () => {
  test('create', () => {
    const logger = new Logger();
    const carFactory= new CarFactory(logger);

    const spy = jest.spyOn(logger, 'log');

    // オプショナルで、Logger.log の挙動を指定したい場合は mockImplementation を呼ぶ
    spy.mockImplementation(() => console.log('log is being called'));

    const carName = 'Toyota'
    carFactory.create(carName);

    // 呼び出されていることをチェック
    expect(logger.log).toHaveBeenCalled();
    // 想定通りの引数で呼び出されていることをチェック
    expect(logger.log).toHaveBeenCalledWith(`creating ${carName} car...`);

    // これでリセットできる
    spy.mockRestore();
  });
});

参考

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?