Take a look at this somewhat contrived Vue component:
<!-- FooBar.vue -->
<template>
<div @click="onClick">{{text}}</div>
</template>
<script>
export default {
name: 'foo-bar',
data() {
return {
text: 'foo'
}
},
methods: {
onClick() {
this.text = 'bar';
}
}
}
</script>
I have written a unit test for this component using Jest:
// FooBar.spec.js
import FooBar from '~/FooBar.vue';
import { shallowMount } from '@vue/test-utils';
import { expect } from 'chai';
describe('FooBar onClick()', () => {
it('should change the text to "bar"', () => {
// Arrange
const target = shallowMount(FooBar);
// Act
target.trigger('click');
// Assert
const div = target.find('div');
expect(div.text()).to.equal('bar');
});
});
The test passes successfully.
However, when running Jest with --coverage
, the summary report shows low coverage:
=============================== Coverage summary ===============================
Statements : 0.1% ( 2/1868 )
Branches : 0% ( 0/1402 )
Functions : 0% ( 0/505 )
Lines : 0.2% ( 2/982 )
================================================================================
It seems that no branches are covered, even though two lines of code are detected as covered.
After adding an if
statement inside onClick()
, one branch was counted as covered by Jest:
onClick() {
if (this.text != undefined) {
this.text = 'bar';
}
}
My question is - Why does Jest / Istanbul not count the code in the onClick()
method as a covered branch?