jaudo
jaudo

Reputation: 2122

vuejs : how to unit test main.ts

I'm using vuejs with typescript, but the question would apply with javascript too.

With vue-test-utils, components are tested using mount or shallowMount. This way, I've been able to unit test the App main component. I'm now wondering how I can unit test the main.ts file, which does already mount the main component:

new Vue({
  router,
  store,
  i18n,
  render: (h) => h(App),
}).$mount('#app');

The unit test would check if App component is really mounted into #app. Unsurprisingly, if I just import main.ts in my test, I get this error:

Cannot find element: #app

Is it possible to do something to create a fake DOM containing an #app element, in which the App component would be mounted?

Upvotes: 2

Views: 4366

Answers (1)

Emptyless
Emptyless

Reputation: 3050

You might use Jest to mock a DOM. This way you could setup multiple tests:

  • initializing: *Verify that without any parameters it can still instantiate the Vue instance (undefined as router, store, etc). Verify that the properties like router etc are added to the prototype
  • Mounting: Create a mock App which renders to your created DOM and verify that the app renders as expected to the correct element

Especially mounting feels more like functional testing instead of unit testing (as it performs more than a 'unit' of work)

EDIT: provide example

// __tests__/main.test.js
'use strict';

test('Can mount app', () => {
  document.body.innerHTML =
    '<div id="app">' +
    '</div>';


  // Executes main file
  require('../src/main');

  const pElement = document.getElementById('example');
  expect(pElement).toBeTruthy();
  expect(pElement.textContent).toEqual('Example');
});

With a main file of:

// main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
}).$mount('#app');

And a App.vue file of:

<template>
  <div id="app">
    <p id="example">Example</p>
  </div>
</template>

Rewriting to Typescript is trivial. A few points to notice:

  1. The App itself is not mocked (Vue.app as injected in main.js). This can be done by creating a separate mock file or using jest.fn() although I have not tested this myself.
  2. The tests are not functional testing it but with small changes can be made to verify small units of work

Upvotes: 4

Related Questions