Testing an MEVN Application Chapter 9
Let's modify the component a little bit to make the tests more understandable. Replace the
contents in Contact.vue with the following code:
<template>
<div class="contact">
<h1>this is contact</h1>
</div>
</template>
Now, let's first create the necessary folder and file to write our tests. Create a file called
Contact.spec.js inside the test/unit/specs directory and add the following contents
to it:
import Vue from 'vue';
import Contact from '@/components/Contact';
describe('Contact.vue', () => {
it('should render correct contents', () => {
const Constructor = Vue.extend(Contact);
const vm = new Constructor().$mount();
expect(vm.$el.querySelector('.contact h1').textContent)
.to.equal('this is contact');
});
});
In the preceding code, we have added a test to check whether the vue component
Contact.vue renders the correct contents or not. We expected to have a div element with
the contact class, and inside it, there should be an h1 tag, which should contain the this
is contact content.
Now, to make sure that our tests run, let's verify that we have the correct script set up to
run the unit test in package.json:
...
"scripts": {
"dev": "webpack-dev-server --inline --progress --config
build/webpack.dev.conf.js",
"start": "nodemon server.js",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js -
-single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit test/e2e/specs",
"build": "node build/build.js",
"heroku-postbuild": "npm install --only=dev --no-shrinkwrap && npm run
build"