Vue/Typescript testing advice

Viewed 144

I need a bit of advice on where to get started. I have been playing around with vue-jest, ts-jest, babel-jest and vue-test-utils (atm all of them are installed).

My jest.config.js file:

const { defaults: tsjPreset } = require('ts-jest/presets');
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
const path = require('path')

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
  moduleNameMapper: {
      '~(.*)$': '<rootDir>/src/$1',
      'components(.*)$': '<rootDir>/src/$1',
      '^vue$': 'vue/dist/vue.common.js'
    },
  transform: {
    ...tsjPreset.transform,
    '^.+\\.(js|jsx)?$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
    '.*\\.(vue|ts|tsx)$': '<rootDir>/node_modules/ts-jest',
  },
  transformIgnorePatterns: ['/src/plugins/*', '/node_modules'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'vue', 'pug'],
  globals: {
    'ts-jest': {
      compiler: 'typescript'
    },
    'vue-jest': {
      pug: {
        'filename': 'pug',
        'doctype': 'html',
        'basedir': './'
      }
    }
  }
};

Component setup looks like this example - Category.Vue:

<template src='./category.pug'         />
<script   src='./category.ts'          />
<style    src='./category.styl' scoped />

With the mentioned files in the same folder.

When I import the .vue file for a test, I get a pug error where the template doesn't compile. Even when changing this to normal html I then get errors on the 'import' lines in the vue file.

When importing the ts file directly, obviously the template is not included so that's also an issue.

So do I need all the packages I have or am I on the wrong track? I am having an issue to get these things working together properly and not sure if I should just start from scratch.

1 Answers

If anyone is still having troubles with it, this is what I used to get it to work:

const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig.json')

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript', // <--- important
  modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'], // <--- important
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths), // <--- important
  testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],

  transform: {
    '^.+\\.vue$': 'vue-jest'
  },
  transformIgnorePatterns: ['/src/plugins/*', '/node_modules'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'vue', 'pug'],
  globals: {
    'ts-jest': {
      compiler: 'typescript'
    },
    'vue-jest': {
      pug: {
        filename: 'pug',
        doctype: 'html',
        basedir: './'
      }
    }
  }
}
 
Related