javascript - vue 2、typescript、mocha 和 karma 的代码覆盖率

标签 javascript typescript testing vuejs2 karma-runner

我们将 Vue 2 与 Typescript 和 webpack 3 结合使用。Vuex 用于状态管理。我们的测试与 Karma 以及 Mocha、Sinon、Expect 和 Avoriaz 一起运行。一切都很好,但我尝试使用 Istanbul 获得代码覆盖率,以更好地直观表示缺少哪些测试。

文件夹结构的小型表示

  • 来源

    • 组件
      • 分享
      • 按钮
        • 按钮.vue
        • 按钮.ts
    • index.ts
    • ...
  • 测试

    • 单位
      • 组件
        • 分享
        • 按钮
          • 按钮.spec.test.ts
    • karma .conf.js
    • karma.coverage.js
    • index.ts
    • ...

按钮.vue

<template>
    <button onClick="handleClick" visible="visible"></button>
</template>

<script lang="ts" src="./button.ts"></script>

button.ts

import { Component, Prop, Vue } from 'vue-property-decorator';

@Component({})
export default class Button extends Vue {

    @Prop({ default: false })
    public visible: boolean;

    private onClick() {
       // do stuff
    }
}

我目前甚至还没有创建 button.spec.ts,这是我试图让团队使用此信息解决的问题,这是代码覆盖率的结果:

Code coverage

项目中的总体覆盖率:

✔ 332 tests completed
=============================== Coverage summary ===============================
Statements   : 43.88% ( 1847/4209 )
Branches     : 36.83% ( 952/2585 )
Functions    : 32.97% ( 456/1383 )
Lines        : 45.28% ( 1732/3825 )
================================================================================

但总的来说,结果实际上根本没有显示代码覆盖率。每个文件都是这样的:

Code lines

我的问题

  • 如何为此获得更好的结果?我是否遗漏了一些关于代码覆盖率的基本信息?
  • 如何编写仅在 .vue 文件中运行的覆盖函数?

其他可能相关的文件:

karma.coverage.js

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['mocha', 'chai', 'sinon'],
    files: [
      'index.ts'
    ],
    reporters: reporters,
    preprocessors: {
      'index.ts': ['webpack']
    },
    webpack: webpackConfig,
    webpackServer: {
      noInfo: true
    },
    junitReporter: {
      outputDir: 'reports/'
    },
    coverageReporter: {
      reporters: [{
        type: 'json',
        dir: '../../coverage/',
        subdir: '.'
      },
      {
        type: 'text-summary'
      },
    ]
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    browsers: ['PhantomJS_custom'],
    customLaunchers: {
        'PhantomJS_custom': {
            base: 'PhantomJS',
            options: {
                windowName: 'my-window',
                settings: {
                    webSecurityEnabled: false
                },
            },
            flags: ['--remote-debugger-port=9003', '--remote-debugger-autorun=yes'],
            debug: false
        }
    },
    phantomjsLauncher: {
        // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
        exitOnResourceError: true
    },
    mime: {
      'text/x-typescript': ['ts']
    },
    singleRun: true,
    concurrency: Infinity
  });
};

unit/index.ts

import 'babel-polyfill';
import Vue from 'vue';

Vue.config.productionTip = false;

function requireAll(r: any): any {
    r.keys().forEach(r);
}

requireAll((require as any).context('./', true, /spec.ts$/));
requireAll((require as any).context('../../src/', true, /^(?!.*(main)).*ts$/));

最佳答案

我建议您应该使用 vue-unit .

例如,您的测试用例可能如下所示:

import { beforeEachHooks, afterEachHooks, mount, waitForUpdate, simulate } from 'vue-unit'
import Button from '@/components/Button'

describe('Button', () => {
  beforeEach(beforeEachHooks)

 it('should render with hidden class if visible is set to false', () => {
     const vm = mount(Button, {
         visible: false //you can ass properties
     })

     expect(vm.$el).to.have.class('hidden') //example assertions, needs chai-dom extension
  })

  afterEach(afterEachHooks)
})

您还可以检查单个方法的结果:

 const vm = mount(Button)

 expect(vm.$el.somemethod('val')).to.be('result')
 //method declared in methods block

您还应该考虑为 chai 添加扩展名,例如 chai-domsinon-chai ,这将允许您创建更灵活的断言:

it('should invoke onClick handler when button is clicked', () => {
    const spy = sinon.spy()

    const vm = mount(Button, {
      onClick: spy
    })

    simulate(vm.$el, 'click')

    expect(spy).to.be.called
  })

可以在karma.conf.js中配置:

//karma.conf.js
...
frameworks: ['mocha', 'chai-dom', 'sinon-chai', 'phantomjs-shim'],
...

恕我直言,您的代码覆盖率配置看起来不错,因此如果您为组件添加测试,它应该会提升您的统计数据。

关于javascript - vue 2、typescript、mocha 和 karma 的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48702171/

相关文章:

Java8 Javascript Nashorn 异常 : no current Global instance for nashorn

javascript - oAuth 2 用于授权和自动登录

JavaScript 正则表达式将 DIV 与特定类相匹配

testing - 错误页面在哪里?

testing - 如何单击 Selenium 2 中的弹出式日历向导?

javascript - 用数组中的随机值填充表单的输入字段(测试)

javascript - ajax调用后如何重新加载脚本?

javascript - jquery 内容切换使用 .slideToggle()

javascript - 带有 Webpack 的 Typescript 中的环境变量

typescript - 有没有办法获得生成器函数的返回类型?