Test-Driven Development
with Vue.js
VueConfTO 2019

Testing is one of the pillars of writing robust software.
Tests should give you confidence that you aren’t shipping broken software.

But... testing can be tough. Especially with UI components.

<template>
<div class="color-picker">
<ul class="swatches">
<li
:key="index"
v-for="(swatch, index) in swatches"
:style="{ background: `#${swatch}` }"
class="swatch"
:class="[
{ active: index === activeSwatch },
{ light: isLight(swatch) }
]"
@click="activeSwatch = index"
>
<check-icon />
</li>
</ul>
<div class="color">
<button
:key="index"
v-for="(mode, index) in colorModes"
class="color-mode"
:class="[{ active: index === activeMode }, `color-mode-${mode}`]"
@click="activeMode = index"
>
{{ mode }}
</button>
</div>
<div class="color-code">{{ activeCode }}</div>
</div>
</template>
<script>
import { rgb, hex, hsl, isLight } from "@/utils/color";
import CheckIcon from "@/assets/check.svg";
const modes = { rgb, hex, hsl };
export default {
components: { CheckIcon },
props: {
swatches: {
type: Array,
default() {
return [];
}
}
},
data() {
return {
activeSwatch: 0,
activeMode: 0,
colorModes: ["hex", "rgb", "hsl"],
isLight
};
},
computed: {
activeCode() {
const activeColor = this.swatches[this.activeSwatch];
const activeMode = this.colorModes[this.activeMode];
return modes[activeMode](activeColor);
}
}
};
</script>
HTML?
CSS classes?
View logic?
Event handlers?
Methods?
Computed properties?
Lifecycle steps?
100% coverage?
Unit vs. integration vs. e2e?

Artwork by Simon Ålander

Artwork by Simon Ålander
Test-Driven Development (TDD)
Popularized by Kent Beck

Red
Write a test that describes an expected behavior, then run it, ensuring it fails.
1
Green
Write the dumbest, most straightforward code you can to make the test pass.
2
Refactor
Refactor the code to make it right.
3
TDD
What does TDD look like with Vue?

Vue Test Utils + Jest

Thinking time!

5 stars to display
Coding time!

What exactly are we testing?
Tests should give you confidence that you aren’t shipping broken software.


Black box testing
Assert only the public interface.
Who are your users?
?

Final user
Developer

With UI components,
your public interface is bigger than you think.
click event
hover event
scroll event
submit event
props
classes
HTML
Do I care about this
if it changes?


TDD lets you write robust tests, not too many and not too few.
1
TDD encourages refactors,
which leads to
better software design.
2
Your software's contract
is infinitely more important
than the way you implement it.
Don't skip the green step.
TDD is much easier to follow with specs.
3
But...
TDD takes
a lot of time.

So, is it worth it?
?
With practice, you will
get faster at TDD.
1
Fixing bugs is far more costly than preventing them.
2



Thank you!
@frontstuff_io
github.com/sarahdayan
bit.ly/2oxVzCO

Test-Driven Development with Vue.js
By Sarah Dayan
Test-Driven Development with Vue.js
VueConf Toronto 2019
- 855