cez*_*zar 5 javascript mocha.js karma-mocha vue.js
我正在努力理解使用 Karma、Mocha 和 Chai 在 Vue.js 中进行单元测试的一些基本概念。
这是我的组件:
VueExample.vue
<template>
<div>
<p>{{ name }}</p>
<input v-model="name">
</div>
</template>
<script>
export default {
name: 'VueExample',
data () {
return {
name: 'Bruce Lee'
};
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
这就是我试图测试它的方式:
VueExample.spec.js
import Vue from 'vue';
import VueExample from "../../../components/VueExample";
describe('VueExample.vue', () => {
let vm;
beforeEach(() => {
const Constructor = Vue.extend(VueExample);
vm = new Constructor().$mount();
});
it('should change the name', done => {
const input = vm.$el.querySelector('input');
input.value = 'Chuck Norris';
expect(vm.$el.querySelector('p').textContent).to.equal('Bruce Lee');
Vue.nextTick(() =>{
expect(vm.$el.querySelector('p').textContent).to.equal('Chuck Norris');
console.log(vm.$el.querySelector('p').textContent);
done();
});
});
});
Run Code Online (Sandbox Code Playgroud)
我使用 Karma 来运行测试,使用 Chai 作为断言库。一切都在karma.conf.js. 当我运行这个测试时,它失败了。标签内的文本<p>不会改变。该console.log命令输出Bruce Lee。
测试是在 Firefox 上运行的。
v-model 依赖于 input 事件,仅通过在 JavaScript 中编辑输入值不会发生该事件。在 Vue 之外也是如此,如下所示:
function logInput(e) {
console.log('input', e.target.value)
}
function update() {
const input = document.querySelector('#input1')
input.value = "foo"
}Run Code Online (Sandbox Code Playgroud)
<input oninput="logInput(event)" id="input1">
<button onclick="update()">Update textbox</button>
<div>Clicking button changes text but does not emit <code>input</code> event. See console.</div>Run Code Online (Sandbox Code Playgroud)
在测试中手动分派输入事件应该可行。在您的示例中,input.dispatchEvent(new Event('input'))设置后执行以下操作input.value:
const input = vm.$el.querySelector('input');
input.value = 'Chuck Norris';
input.dispatchEvent(new Event('input')); // input event required to update v-model
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
890 次 |
| 最近记录: |