Search code examples
javascriptvue.jsunit-testingjestjsvue-test-utils

Testing form reset on Vue with Jest


Testing a form built with Vue using Jest for unit tests. Among the elements I have a reset button (type=reset), which works fine and once clicked it removes all the values already introduced.

However, when unit testing, the button click doesn't seem to clear the values. I don't have a handler for the click, just using the default reset function of the form.

I've also tried using wrapper.emmited('reset'); to no avail, and wrapper.emmitedByOrder(); returns an empty array.

How do I test that the reset button is generated correctly and works as expected?

test('Assert Form Components', async () => {
 const wrapper = mount(FormElement, {
            propsData: {
                message: sampleJSON.formJSON
            }
        })

let resetBtn = wrapper.find('.form-reset');
let requiredInput = wrapper.find('.required-input');
....
requiredInput.setValue('test');
expect(requiredInput.element).toHaveValue('test'); //This passes

await resetBtn.trigger('click');
expect(requiredInput.element).not.toHaveValue('test') //This fails
....

Solution

  • Apparently there were two things missing. First, as @AlexMA suggested, allowing for another tick to let the DOM settle. Second, I needed to attach the wrapper to the DOM. The final code look something like this:

    test('Assert Form Components', async () => {
     const wrapper = mount(FormElement, {
                propsData: {
                    message: sampleJSON.formJSON
                },
                attachTo: document.body
            })
    
    let resetBtn = wrapper.find('.form-reset');
    let requiredInput = wrapper.find('.required-input');
    ....
    requiredInput.setValue('test');
    expect(requiredInput.element).toHaveValue('test'); //This passes
    
    await resetBtn.trigger('click');
    await wrapper.vm.$nextTick()
    expect(requiredInput.element).not.toHaveValue('test') //This works now!
    ....