I have a component where a fieldgroup ( label, input and errors ) is added. The input element is imported dynamically, according to the prop ( settings.input.component
) it receives from the parent component.
And I wanted to test this component, in order to understand if the behavior is correct and performs the intended.
The problem is that I am not able to simulate the import of the input component and as such when I look for the element it does not exist.
Do you have any suggestions?
<template>
<div class="field position--relative">
<label>
....
</label>
<component
:is="inputComponent"
...
/>
</div>
</template>
<script>
export default {
props: {
settings: Object
},
data () {
return {
inputComponent: null,
};
},
...
watch: {
'settings.input.component': {
immediate: true,
deep: false,
async handler ( newComponent ) {
// get input component
this.inputComponent = () => import(
/* webpackChunkName: '[request]' */
`@/components/dynamic/inputs/${newComponent}`
).then( chunk => chunk.default || chunk );
}
},
}
};
</script>
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Vuelidate from 'vuelidate';
import { resetState } from '../helpers/index';
import store from '@/store/';
import BaseField from '@/components/bundles/fields/BaseField';
const localVue = createLocalVue();
localVue.use( Vuex );
localVue.use( Vuelidate );
describe( 'components', () => {
// antes de cada teste, é feito
// o reset a store
beforeEach( resetState );
describe( 'fields', () => {
it( 'add field to store', () => {
// define settings of component
const wrapper = shallowMount( BaseField, {
propsData: {
settings: {
input: {
component: 'InputBasic'
},
}
},
});
// find input
const input = wrapper.find( 'input' );
console.log( input );
console.log( wrapper.html() );
});
});
});
I figured out how to solve the problem. I needed to flush the promises.
Here is an example of the test working.
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import Vuelidate from 'vuelidate';
import VueCompositionAPI from '@vue/composition-api';
import BaseField from '@/components/bundles/fields/BaseField';
import { resetState } from '../helpers/index';
const localVue = createLocalVue();
localVue.use( Vuex );
localVue.use( Vuelidate );
localVue.use( VueCompositionAPI );
function flushPromises () {
return new Promise( resolve => setImmediate( resolve ) );
}
describe( 'components', () => {
beforeEach( resetState );
describe( 'fields', () => {
it( 'add', async () => {
const wrapper = shallowMount( BaseField, {
propsData: {
...
}
},
localVue
});
await flushPromises();
const input = wrapper.find( '.field__input' );
await input.setValue( 'my@mail.com' );
input.trigger( 'blur' );
expect( input.element.value ).toBe( 'my@mail.com' );
expect( wrapper.vm.$data.value ).toBe( 'my@mail.com' );
});
});
});
Flush promises:
function flushPromises () {
return new Promise( resolve => setImmediate( resolve ) );
}