はじめに
この記事では、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"
}