こんにちは。 本日はCypressメモです。
概要
ある時間関連の処理を待機時間なくサクッとテストしたい。
時間関連の処理に含まれるのは以下の関数。
- setTimeout
- clearTimeout
- setInterval
- clearInterval
- Dateオブジェクト
テンプレート
StartIntervalボタンでインターバルを開始し、
10秒ごとにテキストボックスに経過時間を表示します。
StopIntervalボタンで、インターバルを終了します。
html
<button id="startBtn" onclick="startInterval()">StartInterval</button> <button id="stopBtn" onclick="stopInterval()">StopInterval</button> <input type="text" id="intervalText">
let intervalId = null; const intervalText = document.getElementById('intervalText') function startInterval() { let seconds = 0 if (!intervalId) { intervalId = setInterval(() => { intervalText.value = ++seconds * 10 + ' seconds' }, 10000) } } function stopInterval() { clearInterval(intervalId); intervalId = null; }
Cypress
clockを使用することで時間の制御を行うことができます。
使用する際は、まずcy.clock()
でオブジェクトを生成します。
今回は、時間経過に伴うテキストボックスの変化をチェックしたいので
tickを使用して時間を経過させます。
StartIntervalボタンをクリックし、インターバルを開始します。
tick(経過させたい時間)で指定時間経過させます。
describe('サンプル', () => { it('テストパターン', () => { cy.clock() cy.visit('/') cy.get('#startBtn').click() cy.tick(10000) cy.get('#intervalText').should('have.value', '10 seconds') cy.tick(10000) cy.get('#intervalText').should('have.value', '20 seconds') cy.get('#stopBtn').click() }) })
実際、上記内容を確認する場合、20秒待たなければいけないですが
clock、tickを使用して時間経過を制御することで待機時間なくテストができます。
以上です。