Reputation: 2122
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
Reputation: 3050
You might use Jest to mock a DOM. This way you could setup multiple tests:
undefined
as router, store, etc). Verify that the properties like router etc are added to the prototypeEspecially 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:
jest.fn()
although I have not tested this myself.Upvotes: 4