mocha-webpack - dom 没有更新

mocha-webpack - dom is not updating

我正在将 Vue 与 Webpack4 结合使用。并且我安装了mocha-webpack进行测试。但是我从摩卡那里得到了失败的结果。我想 count 正在更新,所以我想通过测试。但是失败了。为什么我得到这样的结果?也许,VirtualDom 没有在测试的 运行 上更新。 increment 方法在测试中调用,但未更新 dom。

测试结果。

 MOCHA  Testing...



  Counter.vue
    1) increments count when button is clicked


  0 passing (26ms)
  1 failing

  1) Counter.vue
       increments count when button is clicked:
     Error: expect(received).toMatch(expected)

Expected substring: "1"
Received string:    "0"
      at Context.it (/path/to/project/static/bundles/main-92a73207cfb074150def.js:7:220294)



 MOCHA  Tests completed with 1 failure(s)

setup.js

require('jsdom-global')();

global.expect = require('expect');

window.Date = Date;

Counter.vue

<template>
  <div>
    <span>{{ count }}</span>
    <button @click="increment()">Increment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0,
    }
  },

  methods: {
    increment() {
      this.count++;
    }
  },
}
</script>

Counter.spec.js

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

describe('Counter.vue', () => {
  it('increments count when button is clicked', () => {
    const wrapper = shallowMount(Counter);
    wrapper.find('button').trigger('click');
    expect(wrapper.find('div span').text()).toMatch('1');
  });
});

package.json

    "jsdom": "^15.1.1",
    "jsdom-global": "^3.0.2",
    "mocha": "^6.2.0",
    "mocha-webpack": "^2.0.0-beta.0",

问题是当您更改 count 时,实际 DOM 并没有在那一刻更新。所以你应该等到 Vue 操作 DOM,因为 Vue 异步执行 DOM 操作。

For example, when you set vm.someData = 'new value', the component will not re-render immediately. It will update in the next “tick”, when the queue is flushed. Most of the time we don’t need to care about this, but it can be tricky when you want to do something that depends on the post-update DOM state.

vue-test-utilds 文档中的代码示例:

it('fetches async when a button is clicked', done => {
  const wrapper = shallowMount(Foo)
  wrapper.find('button').trigger('click')
  wrapper.vm.$nextTick(() => {
    expect(wrapper.vm.value).toBe('value')
    done()
  })
})

我没有使用过 mocha,但我认为您的代码应该如下所示:

describe('Counter.vue', done => {
  it('increments count when button is clicked', () => {
    const wrapper = shallowMount(Counter);
    wrapper.find('button').trigger('click');
    wrapper.vm.$nextTick(() => {
      expect(wrapper.find('div span').text()).toMatch('1');
      done();
    });
  });
});

Async Update Queue.

Testing Asynchronous Behavior.