为什么在使用@ vue / test-utils时,Vue异步观察程序在某些情况下调用了两次?

我有下一个测试(简化):

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

const Component = {
  template: "<p>{{ innerValue }}</p>",props: {
    value: String
  },data() {
    return {
      delayedValue: null,innerValue: null
    };
  },watch: {
    value: {
      immediate: true,async handler(val) {
        console.log(val);
        this.delayedValue = val;
        let text = "";
        if (val) {
          text = await Promise.resolve(val);
        }

        if (this.delayedValue == val) {
          this.innerValue = text;
        }
      }
    }
  }
};

it.only("should update inner value",async () => {
  const wrapper = mount(Component);
  await wait(100);
  wrapper.setProps({ value: "good" });
  await wait(100);
  expect(wrapper.vm.innerValue).be.equal("good");
});

function wait(time) {
  return new Promise(resolve => {
    setTimeout(resolve,time);
  });
}

执行测试时,控制台输出显示:

undefined
good
undefined

平均处理程序被调用3次。第一个undefined对应于组件的初始状态,并因为immediate:true而被调用。第二个'good'是由于setProps的调用引起的,但是问题出在解决Promise之前发生的第三个undefined调用中。导致测试失败。

为什么handler被两次调用?是@vue/test-utils的错误吗?

PS。从观察者中删除任何if语句可修复测试。以及删除immediate:true

coalawang 回答:为什么在使用@ vue / test-utils时,Vue异步观察程序在某些情况下调用了两次?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2899034.html

大家都在问