【问题标题】:Code coverage with vue 2, typescript, mocha and karmavue 2、typescript、mocha 和 karma 的代码覆盖率
【发布时间】:2018-07-20 00:11:20
【问题描述】:

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

文件夹结构的小表示

  • src

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

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

button.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,这是我试图让团队使用此信息解决的问题,这是代码覆盖率的结果:

项目中的一般覆盖范围:

✔ 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 )
================================================================================

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

我的问题

  • 如何获得更好的结果?我是否遗漏了一些关于代码覆盖率的基本知识?
  • 如何编写仅在 .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$/));

【问题讨论】:

    标签: javascript typescript testing vuejs2 karma-runner


    【解决方案1】:

    我建议您使用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'],
    ...
    

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

    【讨论】:

      猜你喜欢
      • 2016-02-29
      • 2013-05-14
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多