Help us understand the problem. What is going on with this article?

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

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)}
})

以上。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした