LoginSignup
4
1

JavaScriptでテストデータを見やすく書けないか試してみた

Last updated at Posted at 2023-12-12

この記事は、Qiita株式会社のカレンダー | Advent Calendar 2023 - Qiitaの12日目の記事です。


JavaScriptで以下のようなテストデータがある場合、プロパティが増えてくると見づらくなるときがあると思います。

const users = [
  { name: 'Yamada Taro', age: 20, email: 'taro@example.com' },
  { name: 'Yamada Hanako', age: 18, email: 'hanako@example.com' },
];

そこで、テストデータをCSVのように記述できないかを試してみたので記事にします。

タグ付きテンプレートを使う

テンプレートリテラルに対してタグをつけるとそれっぽい感じにできました。

const parse = (strings, ...exps) => {
  const header = strings[0];
  const columnNames = header.split(',').map((s) => s.trim());

  const result = [];
  while (exps.length > 0) {
    const obj = {};

    for (let i = 0; i < columnNames.length; i++) {
      const key = columnNames[i];
      const val = exps.shift();
      obj[key] = val;
    }

    result.push(obj);
  }

  return result;
};

const users = parse`
name              , age  , email
${'Yamada Taro'}  , ${20}, ${'taro@example.com'}
${'Yamada Hanako'}, ${18}, ${'hanako@example.com'}
`;

console.log(users);
$ node main.js
[
  { name: 'Yamada Taro', age: 20, email: 'taro@example.com' },
  { name: 'Yamada Hanako', age: 18, email: 'hanako@example.com' }
]

良さそう!

最後に

試してみた後に気がついたのですが、Jestのtest.eachで同様のことができるみたいです。

test.each`
  a    | b    | expected
  ${1} | ${1} | ${2}
  ${1} | ${2} | ${3}
  ${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({ a, b, expected }) => {
  expect(a + b).toBe(expected);
});

これを使えば良さそうですね笑


記事を読んでいただきありがとうございます!
ぜひ、Qiita株式会社のカレンダー | Advent Calendar 2023 - Qiitaを購読設定して、明日の記事もご覧いただけると嬉しいです。

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