ikbal maulana
ikbal maulana

Reputation: 115

Update text field in vue test utils (jest) not working

Hi i am new in jest and unit testing. i want to ask how to set value text input using vue test utils.

shortly I have custom component for text input, its my code

<input
    v-model="local_value"
    @keyup.enter="submitToParent"
    :class="input_class"
    :id="id"
    :disabled="is_disabled"
    :maxlength="max_length"
    :placeholder="placeholder"
    :autocomplete="(is_autocomplete) ? 'on' : 'off'"
    :name="id"
    :ref="id"
  />

and it's my test

it("type something on field", async () => {
        const wrapper = shallowMount(TextInput, {
            propsData: {
                id: "my_input",
            }
        })

        // find component (its work properly) and I want to try inserting some text
        const input = wrapper.findComponent({ref: "my_input"})
        input.element.value = "sample text"
        input.setValue("sample text")

        // the value still empty string (""), idk what happens with my code
        console.log(wrapper.vm.local_value)
        expect(wrapper.vm.local_value).toBe("sample text")


please tell me if you known solution for this problem, thank you for your time

Upvotes: 0

Views: 3078

Answers (2)

Anne
Anne

Reputation: 601

If you're setting the vm's local_value value, you'd want to set it as:

const wrapper = shallowMount(TextInput)
await wrapper.setData({
   local_value: 'sample text'
})

.... if the local_value is declared in data(), or:

const wrapper = shallowMount(TextInput)
await wrapper.setProps({
   local_value: 'sample text'
})

... if the local_value is declared in props() in your component.

Then check it with:

expect(wrapper.vm.local_value).toBe('sample text')

Although that's just the vm value and not rendered value on DOM.

If you'd like to check including the rendered value, you have to declare first the property value on your component for it to be testable:

<input
    v-model="local_value"
    // ... rest of the properties
    :value="local_value"
/>

and test it with:

const input = await wrapper.findComponent({ ref: "my_input" })
expect(input.attributes('value').toBe('sample text')

Ideally, your test will look like this:

it('should have input value' async () => {
  const wrapper = shallowMount(TextInput)
  await wrapper.setProps({  local_value: 'sample text' })
  
  const input = await wrapper.findComponent({ ref: 'my_input' })
  expect(wrapper.vm.local_value).toBe('sample text')
  expect(input.attributes('value').toBe('sample text')
})

👍 Some tip:

You can check the rendered attributes input by commenting all expect and put:

expect(input.attributes('').toBe('random chars here to force an error')

Console will display the errors with the expected attributes output

Upvotes: 0

alextrastero
alextrastero

Reputation: 4300

As far as I know, setValue is async, so you might need to set it with await input.setValue('sample text')

Upvotes: 1

Related Questions