0
1

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でDate()をテスト用に設定する

Posted at

Unit Testを書く際、時刻をテスト用に設定するにはPythonならFreezeGunなどのツールがあります。今回、Ionicのテストを書いていてTypeScriptならどうするのか調べてみました。

部品

Javascript用のSinon.jsというライブラリが良さげです。TypeScriptには@types/sinonというラッパーがあります。

インストール

npm install --save-dev sinon @types/sinon

使い方

割と直球勝負です。単純に時刻を固定化するのならこんな感じ。

import { useFakeTimers } from 'sinon';

let clock = useFakeTimers(new Date(2018, 12, 5, 20, 20, 20).getTime());

// これで時計は2018年12月5日20時20分20秒になります

clock.restore(); // 終わったら必ず解放
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?