programing

vuej에서 단위 테스트

prostudy 2022. 4. 7. 21:13
반응형

vuej에서 단위 테스트

나는 Vuejs의 첫 번째 유닛 테스트를 구성/실행하려고 한다.하지만 구성 문제를 지나칠 수가 없어.도서관을 설치해 보았지만 왠지 자꾸 오류가 난다.

내 코드의 예는 다음과 같다.

내 디렉토리 구조:

   hello/
     dist/
     node_modules/
     src/
      components/
        hello.vue
     test/
      setup.js
      test.spec.js
    .babelrc
     package.json
     webpack.config.js

내 파일 안의 내용

src/procks/hello.부에를 하다

<template> <div> {{message}} </div> </template>
<script>
export default {
  name: 'hello',
  data () { return message: 'Hi' },
  created () {
    // ...
  }
}

테스트/테스트.js

// setup JSDOM
require('jsdom-global')()

// make expect available globally
global.expect = require('expect')

test/test.cs.js

import { shallow } from 'vue/test-utils'
import  { hello} from '../../../src/components/hello.vue'

describe('hello', () => {
  // just testing simple data to see if it works
  expect(1).toBe(1)
})

.babelrc

{
  "env": {
    "development": {
      "presets": [
        [
          "env",
          {
            "modules": false
          }
        ]
      ]
    },
    "test": {
      "presets": [
        [
          "env",
          {
            "modules": false,
            "targets": {
              "node": "current"
            }
          }
        ]
      ],
      "plugins": [
        "istanbul"
      ]
    }
  }
}

꾸러미json

...
  "scripts": {
    "build": "webpack -p",
    "test": "cross-env NODE_ENV=test nyc mocha-webpack --webpack-config webpack.config.js --require test/setup.js test/**/*.spec.js"
  },
"devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "cross-env": "^5.1.1",
    "css-loader": "^0.28.7",
    "file-loader": "^1.1.5",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.6",
    "vue-loader": "^13.5.0",
    "vue-template-compiler": "^2.5.9",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.9.7",
    "jsdom": "^11.3.0",
    "jsdom-global": "^3.0.2",
    "mocha": "^3.5.3",
    "mocha-webpack": "^1.0.0-rc.1",
    "nyc": "^11.4.1",
    "expect": "^21.2.1",
    "@vue/test-utils": "^1.0.0-beta.12"
  },
  ...
"nyc": {
    "include": [
      "src/**/*.(js|vue)"
    ],
    "instrument": false,
    "sourceMap": false
  }

그리고 마지막으로 내 webpack.config.js...

if(process.env.NODE_ENV == "test") {
  module.exports.externals = [ require ('webpack-node-externals')()]
  module.exports.devtool = 'inline-cheap-module-source-map'
}

지금 내가 달리면npm test내 루트 폴더에서hello/다음 오류가 발생하는 경우:

> hello@1.0.0 test C:\Users\john\vue-learn\hello
> npm run e2e


> hello@1.0.0 e2e C:\Users\john\vue-learn\hello
> node test/e2e/runner.js

Starting selenium server... started - PID:  12212

[Test] Test Suite
=====================

Running:  default e2e tests
 × Timed out while waiting for element <#app> to be present for 5000 milliseconds.  - expected "visible" but got: "not found"
    at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)


FAILED:  1 assertions failed (20.281s)

 _________________________________________________

 TEST FAILURE:  1 assertions failed, 0 passed. (20.456s)

 × test

   - default e2e tests (20.281s)
   Timed out while waiting for element <#app> to be present for 5000 milliseconds.  - expected "visible" but got: "not found"
       at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
       at _combinedTickCallback (internal/process/next_tick.js:131:7)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello@1.0.0 e2e: `node test/e2e/runner.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello@1.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\john\AppData\Roaming\npm-cache\_logs\2018-04-03T23_53_15_976Z-debug.log
npm ERR! Test failed.  See above for more details.

왜 이런 일이 일어나는지 모르겠다.처음에 웹 팩 프로젝트를 설치했을 때 npm init 명령으로 테스트 라이브러리를 설치하지 않았으므로 충돌이 발생하지 않았지만 여전히 다음 오류가 발생함:

업데이트(보상금 후)

나는 단지 나의 vuejs 애플리케이션을 테스트하려고 하는 중이다.바라건대 재스민/카르마와 함께.이것들을 간단한 앱에 통합해서 퍼스트 테스트를 실행하는 방법을 아는 사람이 있다면, 나는 거기서 그것을 가져갈 수 있다.내 문제는 시험을 작성하는 것이 아니라 구성하는 것이다.

따라서 먼저 프로젝트에서 테스트를 종료할 수 있도록 할 필요가 없었다.새로 시작하라고 말하고 싶다.

$ npm install -g vue-cli
$ vue init webpack vue-testing

? Project name vue-testing
? Project description A Vue.js project
? Author Tarun Lalwani <tarun.lalwani@payu.in>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner karma
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) yarn

라고 말하다NSetup e2e tests with Nightwatch사용하다Karma를 위해Pick a test runner.

$ npm test

> vue-testing@1.0.0 test /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing
> npm run unit


> vue-testing@1.0.0 unit /Users/tarun.lalwani/Desktop/tarunlalwani.com/tarunlalwani/workshop/ub16/so/vue-testing
> cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run

07 04 2018 21:35:28.620:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
07 04 2018 21:35:28.629:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
07 04 2018 21:35:28.645:INFO [launcher]: Starting browser PhantomJS
07 04 2018 21:35:32.891:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket M1HeZIiOis3eE3mLAAAA with id 44927405

  HelloWorld.vue
    ✓ should render correct contents

PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 1 of 1 SUCCESS (0.061 secs / 0.041 secs)
TOTAL: 1 SUCCESS


=============================== Coverage summary ===============================
Statements   : 100% ( 2/2 )
Branches     : 100% ( 0/0 )
Functions    : 100% ( 0/0 )
Lines        : 100% ( 2/2 )
================================================================================

이제 너의npm test잘 될 거야

여기서 제공하는 오류 로그에 따르면, 여러분이 발견한 실패한 테스트는 엔드 투 엔드 테스트 입니다.실제로 명령을 실행함으로써npm test e2e나이트워치를 사용해서 테스트하는 겁니다.아래 참조/tests/e2e/specs여기서 Vue 애플리케이션이 DOM 요소를 올바르게 생성하는지 확인하는 기본 테스트 파일이 있어야 함app.

시험은 다음과 같아야 한다.

// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

module.exports = {
  'default e2e tests': function (browser) {
    // automatically uses dev Server port from /config.index.js
    // default: http://localhost:8080
    // see nightwatch.conf.js
    const devServer = browser.globals.devServerURL

    browser
      .url(devServer)
      .waitForElementVisible('#app', 5000)
      .assert.elementPresent('.hello')
      .assert.containsText('h1', 'Welcome to Your Vue.js App')
      .assert.elementCount('img', 1)
      .end()
  }
}

당신의 경우 이 테스트는 아마도 당신이 이름붙인 파일을 제거했기 때문에 실패한다.App.vue부에-클립 비계를 통해 생성되는 것.오류는 위의 테스트에서 "app"라는 이름의 DOM 노드가 렌더링되는 경우(즉: .waitForElementVisible('#app', 5000)).

애플리케이션에서 이 div를 더 이상 제공하지 않기 때문에(App.vue 제거로 인해) 기본적으로 실패하고 있다.

여기 두 가지 선택사항이 있다.

  • App.vue 파일 복원(예: Vue 인스턴스를 마운트할 때 'app'로 식별되는 div 생성)

  • 필요에 따라 엔드 투 엔드 편집

이것이 도움이 되기를!

참조URL: https://stackoverflow.com/questions/49640812/unit-testing-in-vuejs

반응형