I tried to test my custom input component. But I don't know how to do it right, because I didn't find any info how to test it. The only thing I found was from this Mocking Form and Field Contexts
My custom component:
<script setup>
import { useField } from 'vee-validate';
import { watch, toRef } from 'vue';
const props = defineProps({
modelValue: {
type: undefined,
default: undefined,
},
type: {
type: String,
default: 'text',
},
label: {
type: String,
default: '',
},
name: {
type: String,
required: true,
},
});
const emit = defineEmits(['update:modelValue']);
const { value, setValue, errorMessage } = useField(toRef(props, 'name'));
watch(
() => value.value,
(newValue) => {
emit('update:modelValue', newValue);
}
);
watch(
() => props.modelValue,
(newValue) => {
setValue(newValue);
}
);
</script>
<template>
<div class="form-group">
<label v-if="props.label" :for="props.label">{{ props.label }}</label>
<input
:id="props.label"
v-model="value"
:name="props.name"
:type="props.type"
class="form-input"
/>
<span v-if="errorMessage" class="form-error" role="alert">{{ errorMessage }}</span>
</div>
</template>
My test file:
import { render, screen, waitFor } from '@testing-library/vue';
import AppField from './AppField.vue';
import { FormContextKey, useForm } from 'vee-validate';
import userEvent from '@testing-library/user-event';
const rednerField = ({ label, type, ...rest } = {}) => {
const options = { props: { name: 'inputName', label, type }, ...rest };
render(AppField, options);
};
const user = userEvent.setup();
const MockedForm = useForm({
validationSchema: {
inputName(value) {
if (value && value.trim()) {
return true;
}
return 'This is required';
},
},
});
describe('showing error', () => {
it('show error if field is invalid', async () => {
rednerField({ label: 'labelName', global: { provide: { [FormContextKey]: MockedForm } } });
const input = screen.getByLabelText('labelName');
user.type(input, ' ');
await waitFor(() => {
expect(screen.getByRole('alert')).toHaveTextContent('This is required');
});
});
});
This test works correctly, but there are warnings in the console: console log from jest
Please tell me if this test is written correctly and how can I get rid of warnings or is this normal ?