10

I am trying to configure/run my first unit test for Vuejs. But I can't get past the configuration issues. I have tried installing the libraries but for some reason I keep getting errors.

Here is what an example of my code looks like:

My directory structure:

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

Contents inside my files

src/components/hello.vue

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

test/setup.js

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

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

test/test.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)
})

.babelrc

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

package.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
  }

and finally my webpack.config.js ...

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

now when I run npm test from my root folder hello/ I get this error:

> 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.

I don't know why this happens. When I installed my webpack project at first I didn't install a testing library with the npm init command so there are no conflicts, but still I get that error:

update (after bounty)

I'm just trying to test my vuejs application. Hopefully with jasmine/karma. If anyone knows how to integrate these into a simple app and run the firsts test, I can take it from there. My problem is not writing tests but configuring it

hidar
  • 5,449
  • 15
  • 46
  • 70
  • Can you provide a minimal repo that you have used? – Tarun Lalwani Apr 06 '18 at 15:31
  • I just installed the webpack-cli with vuejs, and and check the code in my `src/components/hello.vue` example. I basically have a hello world component that I want to test. My issue is not about testing but configuring the test frameworks – hidar Apr 06 '18 at 15:47
  • You want to unit test the components or you want to browser test the rendered application? Because both are different – Tarun Lalwani Apr 06 '18 at 15:48
  • I just want to run test with `npm test` and see the result in my cli – hidar Apr 06 '18 at 15:50
  • You are not understanding the question. There are different types of testing unit testing, integration testing, UI testing. What is your intention what type of testing you want to do? – Tarun Lalwani Apr 07 '18 at 07:08
  • I just want to test that my components do what they are supposed to do. In this case, if I have a method in a component that should return a data on created, I want to test that method/component does what it is supposed to do. It's like unit testing – hidar Apr 07 '18 at 13:03
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/168457/discussion-between-tarun-lalwani-and-hidar). – Tarun Lalwani Apr 07 '18 at 13:15
  • any update on this? – Tarun Lalwani Apr 10 '18 at 06:22
  • Nah, being extra busy with work. This question is for my side project, but don't worry I will test your solution and let you know soon – hidar Apr 10 '18 at 15:45

2 Answers2

4

So first thing you didn't need to enable the end to end testing in your project. I would say start fresh

$ 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

Say N to Setup e2e tests with Nightwatch and use Karma for the 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 )
================================================================================

Now your npm test would work fine.

Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
  • Does your example work with the new webpack? Because I followed this command https://github.com/vuejs/vue-cli#quickstart and did `npm test` but I get an error – hidar Apr 12 '18 at 20:06
  • @hidar, I had test it with the latest `vue-cli` only. Which OS are you using and what error do you get? – Tarun Lalwani Apr 12 '18 at 20:07
  • @hidar, can you run `npm install -g vue-cli` again to make sure you have the latest package. Also make sure to start with a new project – Tarun Lalwani Apr 13 '18 at 05:43
  • sorry the bounty expired before I could award you, I still have no clue about this though so I might add another bounty, but thanks so much for your time – hidar Apr 18 '18 at 00:00
1

According to the error logs you provide here, the failing tests that you spot are the End to End ones. Indeed, by executing the command npm test e2e you're testing using Nightwatch. See under /tests/e2e/specs. Here you should have a default test file checking that your Vue application properly create a DOM element identified as app.

The test should be the following:

// 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()
  }
}

In your case this test is failing because you have probably removed the file named App.vue that is generated through vue-cli scaffolding. The error you get is because the above test checks, with a 5 seconds timeout, if a DOM node named "app" is rendered (i.e.: .waitForElementVisible('#app', 5000)).

Basically it is failing because you actually do not provide this div in your application anymore (due of App.vue removal, maybe).

So you have two options here:

  • restoring the App.vue file (i.e.: create a div identified as 'app' where you mount a Vue instance);

  • editing the end to end according to your needs.

Hope this helps!

P3trur0
  • 3,155
  • 1
  • 13
  • 27
  • i'm not sure I understand. 1) what do you mean `npm test e2e` I only have `npm test` also 2) where should I create a file to put the code? I honestly don't understand one thing. I have the same app as you would download from the webpack cli ... I installed the test library and nothing works ... – hidar Apr 06 '18 at 21:59
  • Hi @hidar, could you please provide the vue-cli command you performed? I said `npm test e2e` because in your error log I see that command. As you may noticed too, your error message says 'Running: default e2e tests'. End to end tests (i.e.: e2e) basically test how your application is rendered on browsers. The test that you see failing is testing if your rendered application contains a div named 'app'. – P3trur0 Apr 07 '18 at 07:12
  • @hidar see also that your failing test is here: `C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js` – P3trur0 Apr 07 '18 at 08:35
  • That's the thing. I don't have `e2e` folder, edit: Now that I looked at my code there is `npm test e2e` this is very strange. I don't use anything related to e2e. ... I am just running `npm test` in my root folder and that's it – hidar Apr 07 '18 at 13:04
  • hi @hidar, the command `npm test` in a default version of application scaffolded using vue-cli comes with both `npm test unit` and `npm test e2e`, so when you launch `npm test` it runs both the unit and the end to end ones. – P3trur0 Apr 07 '18 at 14:03
  • So, what should I do now? I can start a clean project, can you show me the steps to avoid the error? – hidar Apr 12 '18 at 20:21
  • Yes. I suggest you to refer to Tarun Lalwani response where he shows all the steps you need to perform in order to avoid e2e execution. – P3trur0 Apr 13 '18 at 06:08