0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue.js + Jestで「id属性」を使ってコンポーネントを特定し、値をテストする

0
Posted at

はじめに

この記事では、id属性を使ってコンポーネントを特定する方法を、環境情報とあわせて簡潔に解説します。

サンプル

子コンポーネント

<template>
  <p id="child-message">{{ message }}</p>
</template>

<script>
export default {
  name: "ChildComponent",
  props: {
    message: String
  }
};
</script>

親コンポーネント

<template>
  <div>
    <ChildComponent id="child" message="Hello Jest" />
  </div>
</template>

<script>
import ChildComponent from "./ChildComponent.vue";

export default {
  components: {
    ChildComponent
  }
};
</script>

テストコード

import { mount } from '@vue/test-utils';
import Parent from '@/components/Parent.vue';

test('idでコンポーネントを取得して値とpropsを確認する', () => {
  // コンポーネントをマウント
  const wrapper = mount(Parent);

  // id属性を使って子コンポーネントを取得
  const child = wrapper.findComponent('#child');

  // コンポーネントが存在することを確認
  expect(child.exists()).toBe(true);

  // 描画されているテキストの確認
  expect(child.text()).toBe('Hello Jest');

  // propsの値が正しく渡されているか確認
  expect(child.props('message')).toBe('Hello Jest');
});

環境情報

{
  "vue": "3.2.45",
  "@vue/test-utils": "2.2.6",
  "jest": "26.6.3"
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?