Search code examples
javascriptvue.jsvuejs2vue-test-utils

The function of the button is correct, but the unit test reports an error


I can use the button normally on the page:

<template>
    <div>
        <span id='count'>{{count}}</span>
        <button @click="increment">+</button>

    </div>
</template>
<script>
    export default {
        data() {
            return {
                count: 10,
            }
        },
        methods: {
            increment() {
                this.count++;
            }
        }
    }
</script>

But my unit test is not detecting the button's effect. Is it because I made a mistake in unit test, and then click it to report an error?

import { expect } from 'chai';
import { mount } from '@vue/test-utils';

import Counter from '@/components/Counter';

describe('test::::', () => {
    it('test1:::', () => {
        const wrapper = mount(Counter);
        expect(wrapper.find('#count').text()).to.be.equal('10');
        wrapper.find('button').trigger('click');
        expect(wrapper.find('#count').text()).to.be.equal('11');
    });
});

Error message:

AssertionError: expected '10' to equal '11'


Solution

  • The issue is the assertion occurs before the click handler's changes take effect.

    The trigger() method returns a Promise that resolves when the component has updated, so you could make the test callback async, and then await the trigger() call:

    it('test1:::', async () => {
       //...
       await wrapper.find('button').trigger('click');
       expect(wrapper.find('#count').text()).to.be.equal('11');
    });