对我来说,这个问题的症结在于访问组件本身内部的方法。问题here并未说明如何访问组件中的方法。
我有一个Vue组件:
file name: ThisVueFile.test.js
<template>
<div id="ThisStuff">
<span>
Some other stuff is going on here
</span>
</div>
</template>
<script>
import foo from 'bar'
export default {
props: {
ObjectWithStuffInIt: [
{
id: 1
bar: false
},
{
id: 2
bar: false
},
]
},
data: {
foo: "foo"
},
methods: {
doSomeWork: function() {
for (var i = 0; i < ObjectWithStuffInIt.length; i++) {
if (foo === "diddly") {
ObjectWithStuffInIt[i].bar = true;
}
}
}
}
}
</script>
我需要在单元测试中测试doSomeWork
。我只是不知道如何访问该方法。
到目前为止,我已经了解到了这一点:
import {createLocalVue, shallow} from 'vue-test-utils'
import ThisVueFile.test.js from '../../thisPlace/ThatPlace/ThisVueFile.vue'
import Vuex from 'vuex'
const localVue = createLocalVue()
localVue.use(Vuex);
describe('ThisVueFile.test.js', () => {
let user;
let store;
beforeEach(() => {
let getters = {
user: () => user
}
store = new Vuex.Store({ getters })
})
// I need to fill propsData: with some local data here
// because it is server data
// I need to have access to the method
// I need to use local data for `foo` in the test.
it(' When foo is set to -diddly- then set bar to true ', () => {
foo = "diddly";
// run the method in the component here
doSomeWork();
expect(OjbectWithStuffInIt[0].bar.equals(true));
})
})
答案 0 :(得分:4)
propsData
使用shallowMount
(或mount
)创建组件包装时,可以将options
与初始propsData
一起传递:
import MyComponent from "@/components/MyComponent";
//...
it('...', () => {
const wrapper = shallowMount(MyComponent, {
localVue,
propsData: {
ObjectWithStuffInIt
}
});
})
包装器通过其vm
属性提供对组件实例的访问,因此您可以直接使用以下方法调用该方法:
wrapper.vm.doSomeWork()
类似地,您可以直接访问组件的数据属性:
wrapper.vm.foo = 'diddly'
总的来说,您的测试可能与此类似:
import { createLocalVue, shallowMount } from "@vue/test-utils";
import MyComponent from "@/components/MyComponent";
describe("MyComponent", () => {
it(" When foo is set to -diddly- then set bar to true ", () => {
const ObjectWithStuffInIt = [
{ id: 200, bar: false },
{ id: 300, bar: false }
];
const localVue = createLocalVue();
const wrapper = shallowMount(MyComponent, {
localVue,
propsData: {
ObjectWithStuffInIt
}
});
wrapper.vm.foo = "diddly";
// run the method in the component here
wrapper.vm.doSomeWork();
expect(ObjectWithStuffInIt[0].bar).toBe(true);
});
});