如何访问Vuejs方法以使用Jest进行测试?

时间:2019-02-25 14:32:29

标签: unit-testing vue.js jestjs

我有以下文件:deposit-form.js

使用以下代码:

new Vue({
    el: '#app',
    data: {
        title: 'title',
        depositForm: {
            chosenMethod: 'online',
            payMethods: [
                { text: 'Already paid via Venmo', value: 'venmo' },
                { text: 'Pay online', value: 'online' },
                { text: 'In-person payment', value: 'person' }
            ],         
        },
    },
    methods: {
        submitDeposit: function() {
            $.ajax({
                url: 'http://localhost:8000/api/v1/deposit/',
                type:'post',
                data: $('#deposit-form').serialize(),
                success: function() {
                    $('#content').fadeOut('slow', function() {
                        // Animation complete.
                        $('#msg-success').addClass('d-block');
                    });
                },
                error: function(e) {
                    console.log(e.responseText);
                },
           });
        },
        showFileName: function(event) {
            var fileData =  event.target.files[0];
            var fileName = fileData.name;
            $('#file-name').text('selected file: ' + fileName);
        },
    },
});

我在如何设置Jest,如何在“方法”中导入VueJs函数以使用Jest进行测试方面遇到问题。

我在deposit-form.test.js上的代码应该如何?

1 个答案:

答案 0 :(得分:0)

您需要做的第一件事是导出Vue应用程序实例。

// deposit-form.js

import Vue from 'vue/dist/vue.common';

export default new Vue({
    el: '#app',
    data: {...},
    ...
});

现在,您可以在规范文件中使用此代码。但是现在您需要在运行测试之前拥有#app元素。可以使用jest设置文件来完成。我将解释为什么需要它。将主文件(deposit-form.js)导入测试时,将使用new在主文件中创建Vue实例。 Vue尝试将应用程序安装到#app元素中。但是此元素不在您的DOM中。这就是为什么您需要在运行测试之前添加此元素。

在此文件中,您也可以全局导入jQuery以在测试中使用它,而无需单独导入。

// jest-env.js

import $ from 'jquery';

global.$ = $;
global.jQuery = $;

const mainAppElement = document.createElement('div');
mainAppElement.id = 'app';
document.body.appendChild(mainAppElement);

必须在package.json的jest配置部分中指定jest设置文件。

// package.json

{
    ...,
    "dependencies": {
        "jquery": "^3.3.1",
        "vue": "^2.6.7"
    },
    "devDependencies": {
        "@babel/core": "^7.0.0",
        "@babel/plugin-transform-modules-commonjs": "^7.2.0",
        "@babel/preset-env": "^7.3.4",
        "@vue/test-utils": "^1.0.0-beta.29",
        "babel-core": "^7.0.0-bridge.0",
        "babel-jest": "^24.1.0",
        "babel-loader": "^8.0.5",
        "babel-preset-vue": "^2.0.2",
        "jest": "^24.1.0",
        "vue-jest": "^3.0.3",
        "vue-template-compiler": "^2.6.7",
        "webpack": "^4.29.5",
        "webpack-cli": "^3.2.3"
    },
    "scripts": {
        "test": "./node_modules/.bin/jest --passWithNoTests",
        "dev": "webpack --mode development --module-bind js=babel-loader",
        "build": "webpack --mode production --module-bind js=babel-loader"
    },
    "jest": {
        "moduleFileExtensions": [
            "js",
            "json",
            "vue"
        ],
        "transform": {
            "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
            ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
        },
        "setupFiles": [
            "<rootDir>/jest-env.js"
        ]
    }
}

此外,您可能需要配置Babel以在项目和测试中使用ES6的功能。如果您在代码中遵循commonjs样式,则没有必要。基本的.babelrc文件包含以下代码:

// .babelrc

{
    "presets": [
        [
          "@babel/preset-env",
          {
            "useBuiltIns": "entry",
            "targets": {
              "browsers": [
                "last 2 versions"
              ]
            }
          }
        ],
        "vue",
    ],
    "plugins": [
        "@babel/plugin-transform-modules-commonjs",
    ]
}

现在您可以编写测试了。

// deposit-form.test.js

import App from './deposit-form';

describe('Vue test sample.', () => {
    afterEach(() => {
        const mainElement = document.getElementById('app');

        if (mainElement) {
            mainElement.innerHTML = '';
        }
    });

    it('Should mount to DOM.', () => {
        // Next line is bad practice =)
        expect(App._isMounted).toBeTruthy();

        // You have access to your methods
        App.submitDeposit();
    });
});

我的建议是学习Vue Test Utils Guides,并开始将您的代码分为几个部分。使用当前的方法,您将失去所有组件的功能以及测试vue应用程序的能力。


我更新了我的答案。从我对答案的评论中可以理解,您将页面上的库连接为单独的文件。这是我的错误。我没有问是否正在使用构建系统。我的示例中的代码是使用ECMA-2015标准编写的。但是,不幸的是,浏览器没有完全支持它。您需要一个将我们的文件转换为浏览器可以理解的格式的编译器。听起来很难。但这不是问题。作为响应,我更新了文件package.json的内容。现在只需要为程序集创建输入文件并运行程序集本身即可。

输入文件很简单。

// index.js

import './deposit-form';

从终端使用以下命令开始构建。

# for development mode
$ yarn run dev
# or
$ npm run dev

# for production mode
$ yarn run build
# or
$ npm run build

输出文件将放置在目录./dist/中。现在,您只需要连接一个文件,而不是单独的文件。它包含该库和您的代码所需的所有内容。

我使用webpack构建。可以在documentation中找到有关它的更多信息。您可以在this article中找到很好的例子。

相关问题