Test Vue Components with


Jest

Components
Vuex
Services
Basics
Wrapper and WrapperArray
- Vue Component
- find & findAll
Local Vue
Creates a vue instance to add components, mixins or install plugins to use through the test
Tip: Vuex
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
const localVue = createLocalVue()
localVue.use(Vuex)Components
Rendering Components
Testing Props
<template>
<div>
<span v-if="isAdmin">Admin Privileges</span>
<span v-else>Not Authorized</span>
<button>
{{ msg }}
</button>
</div>
</template>
<script>
export default {
name: "SubmitButton",
props: {
msg: {
type: String,
required: true
},
isAdmin: {
type: Boolean,
default: false
}
}
}
</script>import { shallowMount } from '@vue/test-utils'
import SubmitButton from '@/components/SubmitButton.vue'
describe('SubmitButton.vue', () => {
it("displays a non authorized message", () => {
const msg = "submit"
const wrapper = shallowMount(SubmitButton,{
propsData: {
msg: msg
}
})
console.log(wrapper.html())
expect(wrapper.find("span").text()).toBe("Not Authorized")
expect(wrapper.find("button").text()).toBe("submit")
})
})In fact, test all vue properties
Simulate User Input
<template>
<div>
</div>
</template>
<script>
export default {
name: "Emitter",
methods: {
emitEvent() {
this.$emit("myEvent", "name", "password")
}
}
}
</script>
<style scoped>
</style>import Emitter from "@/components/Emitter.vue"
import { shallowMount } from "@vue/test-utils"
describe("Emitter", () => {
it("emits an event with two arguments", () => {
const wrapper = shallowMount(Emitter)
wrapper.vm.emitEvent()
console.log(wrapper.emitted())
})
})Try to isolate Component with mocks and stubs
Mock
Create a call to see interaction between two parts. Can be tracked
Stub
"Fake" a non tracked call, components can be stubbed
deck
By Xavi Sanchez Mir
deck
- 206