Vue-test-utils:在单个测试中多次使用 $nextTick

Vue-test-utils: using $nextTick multiple times in a single test

我正在为组件中的 vuelidate 验证编写单元测试。我发现 $touch() 方法是异步调用的,所以我需要为 expect() 使用 $nextTick()。当我需要两个 nextTick()s 两个 expect()s.

时,问题就出现了
describe('Validations', () => {
    let data
    let myComponent
    beforeEach(() => {
        data = () => {
            propertyABC = 'not allowed value'
        }
        myComponent = localVue.component('dummy', {template: '<div></div>', validations, data})

    it('Properly validates propertyABC', (done) => {
        Vue.config.errorHandler = done
        let wrapper = mount(myComponent, {localVue})
        wrapper.vm.$v.$touch()

        wrapper.vm.$nextTick(() => {
            expect(wrapper.vm.$v.propertyABC.$error).to.be.true
            # fails, because propertyABC === 'allowed value', adn thus $error is false
            done()
        }

        wrapper.vm.propertyABC = 'allowed value'
        wrapper.vm.$v.propertyABC.$touch()

        wrapper.vm.$nextTick(() => {
            expect(wrapper.vm.$v.proprtyABC.$error).to.be.false
            done()
        }
    })
})

我怎样才能 运行 这个测试而不把它分成两个单独的测试?我认为嵌套 $nextTick() 可能有效,但对于更多的测试来说它不灵活。

如果您可以使用 async functions,那么您可以 await 调用 $nextTick。这将避免必须嵌套它们并将所有内容都放在同一个测试中。

像这样:

describe('Validations', () => {
  let data;
  let myComponent;
  beforeEach(() => {
    data = () => ({ propertyABC = 'not allowed value' });
    myComponent = localVue.component('dummy', {template: '<div></div>', validations, data});
  });

  it('Properly validates propertyABC', async  () => {
    let wrapper = mount(myComponent, {localVue});
    wrapper.vm.$v.$touch();

    await wrapper.vm.$nextTick();

    expect(wrapper.vm.$v.propertyABC.$error).to.be.true;

    wrapper.vm.propertyABC = 'allowed value';
    wrapper.vm.$v.propertyABC.$touch();

    await wrapper.vm.$nextTick();

    expect(wrapper.vm.$v.proprtyABC.$error).to.be.false;
  })
})

另一种方法是使用 flushPromises。

import flushPromises from 'flush-promises';
...

test('some async test', async () => {
  const wrapper = mount(MyComponent, { localVue });
  wrapper.vm.$v.$touch();
  await flushPromises();
});

flushPromises() returns 承诺本身,因此当您 need/want 使用 .then().then() 等链接事物时它很有用...