0
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 1 year has passed since last update.

【Jest】findAllとfilterを使い、Component内に特定の要素が表示されないことをテストする【Vue】

Last updated at Posted at 2021-12-03

この記事で説明すること

表題の通りです。
例えば、「v-if で制御している箇所がelseの場合に表示されないこと」をテストしたい時に使える方法です。

findAllfilter を使います。

テスト対象のコンポーネント

Sample.vue

<template>
  <div>あああ</div>
  <div>いいい</div>
  <div>ううう</div>
  <div>えええ</div>
  <div>おおお</div>
</template>

※適当ですみませんw

テストを書いてみる

例えば、「かかか」という要素が表示されないことをテストしたい時は、以下のように書きます。

sample.spec.ts

// ..
const wrapper = mount(Sample)
expect(wrapper.findAll('div').filter((w) => w.text() === 'かかか').length).toBe(0);

// ..

ちょっと解説

findAll('div')div要素を全て返す
filter((w) => w.text() === 'かかか')textかかかを持つ要素を返す

まとめると、上記で空のWrapperArrayを返してくれるので、「lengthが0」であるテストを書いてます。

findAll('div').at(6).isExist() などでも書くことができますが、atで指定してしまうと、div要素の数が変わった時にテストも修正しなければいけなくなってしまう(+書き方がイケてない)ので、上記の書き方の方が良いかなぁと思います!

参考

公式 - filterについて

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