Imagine we have a simple Bootstrap powered HTML form within a custom Vue component named MyForm.vue
<template>
<form>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</template>
The unit test to check if the template is rendered correctly is quite straightforward
describe('MyForm', () => {
let wrapper;
beforeEach(...);
it('Should be rendered', () => {
let field = wrapper.find('#email');
expect(field.element.value).toEqual('');
});
});
We can access the value of field.element.value
since field.element
is an HTMLInputElement with the attribute value
.
If we need to access an attribute of a more complex component like b-form-input, which is Bootstrap-Vue's default input element, how should we go about it? Do we cast the HtmlElement
to BFormInput
?
<template>
<b-form>
<b-form-group label="Email">
<b-form-input type="email" id="email"></b-form-input>
</b-form-group>
<b-button type="submit" variant="primary">Submit</button>
</b-form>
</template>
How do we test non-native components, especially when using TypeScript for type-safety? Any suggestions?
Edit 03/01/2020
In response to muka.gergely's answer, I came across this article. By default, shallowMount
stubs all child components, including event handling. However, shallowMount
allows for manual unstubbing of components, such as b-form
and b-button
for testing submit events.
const stubs = { // Intended for custom stubs but used here to unstub components
BButton,
BForm,
};
wrapper = shallowMount<MyComponent>(MyComponent, {stubs});
This approach ensures that these components are rendered instead of being stubbed, while other components like b-form-input
remain stubbed automatically.