代码之家  ›  专栏  ›  技术社区  ›  hidar

vuejs中的单元测试

  •  10
  • hidar  · 技术社区  · 6 年前

    我正在尝试为Vuejs配置/运行我的第一个单元测试。但我无法克服配置问题。我曾尝试安装这些库,但由于某些原因,我不断出错。

    下面是我的代码示例:

    我的目录结构:

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

    我的文件中的内容

    src/组件/您好。vue

    <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')
    

    测试/测试。spect。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)
    })
    

    .巴别塔LRC

    {
      "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
      }
    

    最后是我的网页。配置。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.
    

    我不知道为什么会这样。最初安装webpack项目时,我没有使用npm init命令安装测试库,因此没有冲突,但仍然出现了错误:

    更新(悬赏后)

    我只是想测试我的vuejs应用程序。希望有茉莉花/因果报应。如果有人知道如何将这些集成到一个简单的应用程序中并运行firsts测试,我可以从那里开始。我的问题不是编写测试,而是配置它

    2 回复  |  直到 6 年前
        1
  •  4
  •   Tarun Lalwani    6 年前

    因此,首先,您不需要在项目中启用端到端测试。我会说重新开始

    $ 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
    

    N Setup 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 会很好的。

        2
  •  1
  •   P3trur0    6 年前

    根据您在此处提供的错误日志,您发现的失败测试是端到端测试。实际上,通过执行命令 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 这是通过vue cli脚手架生成的。出现的错误是因为上述测试在5秒超时的情况下检查是否呈现了名为“app”的DOM节点(即: .waitForElementVisible('#app', 5000) ).

    基本上,它是失败的,因为您实际上不再在应用程序中提供此div(可能是由于App.vue被删除)。

    因此,您有两个选择:

    • 正在还原应用程序。vue文件(即:创建一个标识为“app”的div,在其中装载vue实例);

    • 根据需要编辑端到端。

    希望这有帮助!

    推荐文章