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

Cypressで非同期処理の完了を待ちたい

Posted at

ユーザー新規登録をテストでハマったのでメモ。
ユーザー情報はFirebase Authenticationで管理しており、新規登録画面でユーザー登録し、Firebase上にユーザーがきちんと登録されていることを確認後、テスト終了時にFirebase上のユーザー情報を削除したい。

普通にこんな感じでやっても動かない。

const deleteUser = () => {
  return new Promise(resolve => {
    firebase.auth().onAuthStateChanged(user => {
      resolve(user);
    });
  })
}
deleteUser().then(user => user.delete())

その後ドキュメントを見直して、Cypress.Promiseを発見したので試してみる。
https://docs.cypress.io/api/utilities/promise.html#Syntax

const deleteUser = () => {
  return new Cypress.Promise(resolve => {
    // 同じ
  })
}
deleteUser().then(user => user.delete())

これも動かない。
Custom Commandsを使うと同期的に実行してくれるみたい。
https://docs.cypress.io/api/cypress-api/custom-commands.html#Syntax

To get your function into the Cypress pipeline you can use custom commands. The documentation doesn't state it, but you can return a Cypress.Promise from them.

https://stackoverflow.com/questions/52154037/wait-for-an-own-function-which-returns-a-promise-before-tests-are-executed

Cypress.Commands.add('deleteFirebaseAccount', () => {
  const firebase = setupFirebase();

  return new Cypress.Promise(resolve => {
    firebase.auth().onAuthStateChanged(user => {
      resolve(user);
    });
  });
});

afterEach(() => {
  cy.deleteFirebaseAccount().then(user => user.delete())
});

こんな感じで書いてあげたらうまく動いた。

1
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
1
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?