2
2

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.

CodeceptJSでデータドリブンテストを行うときの注意点

Posted at

CodeceptJSはデータドリブンテストをサポートしており、配列や専用の DataTable オブジェクトを渡すことで、一つのシナリオを異なるデータで複数回実行することができます。
例えば、下記の例ではhoge@example.com``fuga@example.comの2つのアカウント情報でログインのテストを実行します。


const accounts = [
  { email: 'hoge@example.com', password: 'secret' },
  { email: 'fuga@example.com', password: '123456' },
]

Feature('Data Driven Sample')

Data(accounts).Scenario('Can Login', (I, current) => {
  
  // Data()に渡した配列が一つずつcurrentという変数に渡される

  I.fillField('email', current.email)
  I.fillField('password', current.password)
  I.click('Login')

})

CodeceptJSは、テストの実行を1ファイルごとに同期的に行いますが、シナリオの登録そのものはファイル読込直後に一括で行われるようです(コード読んでないので挙動から推測してますが……)。
そのため、シナリオAで実行した結果をグローバル変数に格納し、Data()経由で別のシナリオを実行するのに使うことはできません。


let accounts = {}

Feature('Bad Data Driven Sample')

Scenario('Can fetch account data', (I) => {

  /** 
   * GET '/accounts' は以下の配列を返す
   * [
   *   { email: 'hoge@example.com', password: 'secret' },
   *   { email: 'fuga@example.com', password: '123456' },
   * ]
   */

  accounts = (await I.sendGetRequest('/accounts'))
})

// accountsに渡ってくるのは {} のため、このテストは失敗します
Data(accounts).Scenario('Can Login', (I, current) => {
  
  I.fillField('email', current.email)
  I.fillField('password', current.password)
  I.click('Login')

})

上記のようなことをやりたい場合、シナリオの外で GET /accounts を実行する必要がありますが、シナリオの外で I.sendGetRequest() を実行することは出来ないので、Axiosなどを使って自前で実装する必要があります。


/** 
 * GET '/accounts' は以下の配列を返す
 * [
 *   { email: 'hoge@example.com', password: 'secret' },
 *   { email: 'fuga@example.com', password: '123456' },
 * ]
 */
const accounts = ( async () => axios.get('/accounts') )()

Feature('Use Axios')

Data(accounts).Scenario('Can Login', (I, current) => {

  I.fillField('email', current.email)
  I.fillField('password', current.password)
  I.click('Login')

})

以上、コネタでした。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?