LoginSignup
3
2

More than 3 years have passed since last update.

mochaにおける非同期処理の3つのテストパターン

Last updated at Posted at 2019-12-20

promiseオブジェクトをreturnするパターン

itのコールバック関数内でpromiseオブジェクトをreturnした場合、promiseのresolve(もしくはreject)を待ちます。

it('asynchronous process 1', () => {
  return new Promise((resolve, reject) => {
    try {
      setInterval(() => {
        expect(1).equal(1)
        resolve();
      }, 1000)
    } catch (e) {
      reject(e);
    }
  })
})

doneを使って、処理の終わりを通知するパターン

あとのパターンは、以下のような重い処理を呼び出す前提です。

// 1秒かかる重い処理
const heavyJob = () => {
  return new Promise(resolve => {
    setInterval(resolve, 1000);
  })
}

doneを引数にとり、そのdoneを使って処理の終了を伝えます。
ちなみに、doneを引数に取りながら未使用だった場合、エラーが発生します。

it('asynchronous process 2', (done) => {
  try {
    heavyJob().then(() => {
      expect(1).equal(1)
      done();
    }, e => done(e))
  } catch (e) { done(e) }
})

async/awaitを使うパターン

環境が許す場合は、async/await を使うことができます。

it('asynchronous process 3', async () => {
  try {
    await heavyJob();
    expect(1).equal(1)
  } catch (e) { throw e }
})

許可されない書き方

以下の書き方をすると、例外が発生します(Error: Resolution method is overspecified. Specify a callback or return a Promise; not both.)

it('anti-pattern', async (done) => {
  try {
    await heavyJob();
    expect(1).equal(1)
    done()
  } catch (e) { done(e)}
})

以上。

3
2
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
3
2