简体   繁体   中英

setTimeout in watchers not run with vue-test-utils

I have a very simple component to explain my issue here. When I am using setTimeout in watchers, test don't run as expected.

ComponentTest.vue:

<template>
  <input v-model="value" type="text">
</template>
<script>
  export default {
    name: 'ComponentTest',
    data() {
      return {
        value: '',
        valueHasChanged: false
      };
    },
    watch: {
      value() {
        console.log('value has changed');
        setTimeout(() => {
          console.log('timeout in watcher');
          this.valueHasChanged = true;
        }, 0);
      }
    },
    created() {
      setTimeout(() => {
        console.log('timeout in created method');
      }, 2000);

      this.$watch('value', () => {
        setTimeout(() => {
          console.log('timeout in created method in $watch');
          this.valueHasChanged = true;
        }, 0);
      });
    }
  };

</script>

ComponentTest.spec.ts:

import { shallowMount } from '@vue/test-utils';
import ComponentTest from './ComponentTest.vue';

beforeEach(() => {
  jest.useFakeTimers();
});

describe('ComponentTest', () => {
  it('should test', () => {
    const wrapper: any = shallowMount(ComponentTest, {});
    wrapper.vm.value = 'test';
    wrapper.vm.value = 'test1';
    jest.advanceTimersByTime(100000);
    expect(wrapper.vm.valueHasChanged).toBe(true);
  });
});

valueHasChanged status doesn't change in the tests even though I use fake timers. And I don't see any console.log that are inside watchers.

Is this a bug from vue-test-utils (or jest), or am I missing something?

wrapper.vm.value = 'test';
wrapper.vm.value = 'test1';

You have to change this part of your code. Instead of updating the data properties as you've done, do it using the API offered by vue test utils .

Those lines can be replaced by,

await wrapper.setData({ value: 'test' });
await wrapper.setData({ value: 'test1' });

API reference - https://next.vue-test-utils.vuejs.org/api/#setdata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM