如何使用Jest对Vue.js组件中的方法进行单元测试

单元测试

StafanDavaid

2020-03-12

我正在尝试对组件方法进行单元测试。这里的问题并未提出如何从单元测试中访问组件方法。

具体来说,给定下面的Vue组件,如何doSomeWork()从单元测试中访问

Vue组件:

<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>

我的测试代码:

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));
    })
})

第1238篇《如何使用Jest对Vue.js组件中的方法进行单元测试》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android