Programing

부에 2, 활자, 모카 및 카르마를 포함한 코드 적용 범위

c10106 2022. 5. 20. 21:14
반응형

부에 2, 활자, 모카 및 카르마를 포함한 코드 적용 범위

우리는 Typecript 및 웹팩 3과 함께 Vue 2를 사용하고 있다.Vuex는 국가 관리에 사용된다.우리의 테스트는 모카, 시논, 에베레스트, 아보리아즈와 함께 카르마와 함께 실행된다.모든 것이 훌륭하지만 나는 어떤 테스트가 누락되었는지 시각적으로 더 잘 표현하기 위해 이스탄불을 이용한 코드 커버리지를 작동시키려 노력한다.

폴더 구조의 작은 표현

  • src

    • 구성 요소들
      • 공유했습니다.
      • 단추를 채우다
        • button.vue
        • button.ts
    • 인덱스.ts
    • ...
  • 시험

    • 구성 단위
      • 구성 요소들
        • 공유했습니다.
        • 단추를 채우다
          • button.spec.test.ts
    • 업보.conf.js
    • 업보. 업보.js
    • 인덱스.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.tts를 전혀 만들지 않았다. 나는 이 informatoin을 사용하여 팀이 다루게 하려고 노력하고 있다. 그리고 이것은 코드 커버리지의 결과물이다.

코드 적용 범위

프로젝트 전반의 적용 범위:

✔ 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 파일에서만 실행되는 기능을 어떻게 코드화하시겠습니까?

관련될 수 있는 기타 파일:

업보. 업보.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-dom)에 확장을 추가하는 것을 고려해야 하며, 이를 통해 다음과 같은 보다 유연한 주장을 만들 수 있다.

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'],
...

IMHO 코드 적용 범위 구성이 괜찮아 보이므로, 구성 요소에 대한 테스트를 추가하면 통계량이 향상될 것이다.

참조URL: https://stackoverflow.com/questions/48702171/code-coverage-with-vue-2-typescript-mocha-and-karma

반응형