DEV Community

Cover image for Vite vue ts tailwind template: Setup Jest coverage and add tests
Sardorbek Imomaliev
Sardorbek Imomaliev

Posted on

Vite vue ts tailwind template: Setup Jest coverage and add tests

Enable and setup tests coverage

  1. To enable coverage in Jest we need to set collectCoverage in our configs to true.
  2. By default, coverage will run on all files. To avoid that, let's configure Jest to collect coverage only on our src dir and only on actual code files.
  3. Update our jest.config.js

    diff --git a/jest.config.js b/jest.config.js
    index 0b17c77..f718135 100644
    --- a/jest.config.js
    +++ b/jest.config.js
    @@ -9,4 +9,12 @@ module.exports = {
       moduleNameMapper: {
         '^@/(.*)$': '<rootDir>/src/$1',
       },
    +  collectCoverage: true,
    +  collectCoverageFrom: [
    +    'src/**/*.{js,jsx,ts,tsx,vue}',
    +    // do not cover types declarations
    +    '!src/**/*.d.ts',
    +    // do not cover main.ts because it is not testable
    +    '!src/main.ts',
    +  ],
     }
    
  4. git add -u

  5. git commit -m 'enable jest coverage'

  6. Run tests with enabled coverage

    $ npm run test
    
    > vite-vue-typescript-starter@0.0.0 test
    > jest
    
     PASS  tests/unit/HelloWorld.spec.ts
      HelloWorld.vue
        ✓ renders props.msg when passed (41 ms)
    
    -----------------|---------|----------|---------|---------|-------------------
    File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
    -----------------|---------|----------|---------|---------|-------------------
    All files        |   57.14 |      100 |     100 |   57.14 |
     src             |       0 |      100 |     100 |       0 |
      App.vue        |       0 |      100 |     100 |       0 | 7-10
     src/components  |     100 |      100 |     100 |     100 |
      HelloWorld.vue |     100 |      100 |     100 |     100 |
    -----------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        3.88 s
    Ran all test suites.
    

Update .gitignore for coverage and other common files

  1. When we have created vue-ts template there was initial .gitignore file which was created as a part of vite/vue-ts scaffold.
  2. But this .gitignore doesn't include common configuration for things like coverage. And that is why we get this message when we check our git status.

    $ git status
    On branch main
    Your branch is ahead of 'origin/main' by 2 commits.
      (use "git push" to publish your local commits)
    
    Changes to be committed:
      (use "git restore --staged <file>..." to unstage)
            new file:   tests/unit/App.spec.ts
    
    Untracked files:
      (use "git add <file>..." to include in what will be committed)
            coverage/
    
  3. coverage/ folder contains generated reports. We should add it to .gitignore. To do that we will use Node.gitignore from very helpful .gitignore collection repo by github.

    Expand .gitignore diff
    diff --git a/.gitignore b/.gitignore
    index d451ff1..0b799e4 100644
    --- a/.gitignore
    +++ b/.gitignore
    @@ -1,5 +1,122 @@
    -node_modules
    -.DS_Store
    +# Logs
    +logs
    +*.log
    +npm-debug.log*
    +yarn-debug.log*
    +yarn-error.log*
    +lerna-debug.log*
    +.pnpm-debug.log*
    +
    +# Diagnostic reports (https://nodejs.org/api/report.html)
    +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
    +
    +# Runtime data
    +pids
    +*.pid
    +*.seed
    +*.pid.lock
    +
    +# Directory for instrumented libs generated by jscoverage/JSCover
    +lib-cov
    +
    +# Coverage directory used by tools like istanbul
    +coverage
    +*.lcov
    +
    +# nyc test coverage
    +.nyc_output
    +
    +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
    +.grunt
    +
    +# Bower dependency directory (https://bower.io/)
    +bower_components
    +
    +# node-waf configuration
    +.lock-wscript
    +
    +# Compiled binary addons (https://nodejs.org/api/addons.html)
    +build/Release
    +
    +# Dependency directories
    +node_modules/
    +jspm_packages/
    +
    +# Snowpack dependency directory (https://snowpack.dev/)
    +web_modules/
    +
    +# TypeScript cache
    +*.tsbuildinfo
    +
    +# Optional npm cache directory
    +.npm
    +
    +# Optional eslint cache
    +.eslintcache
    +
    +# Microbundle cache
    +.rpt2_cache/
    +.rts2_cache_cjs/
    +.rts2_cache_es/
    +.rts2_cache_umd/
    +
    +# Optional REPL history
    +.node_repl_history
    +
    +# Output of 'npm pack'
    +*.tgz
    +
    +# Yarn Integrity file
    +.yarn-integrity
    +
    +# dotenv environment variables file
    +.env
    +.env.test
    +.env.production
    +
    +# parcel-bundler cache (https://parceljs.org/)
    +.cache
    +.parcel-cache
    +
    +# Next.js build output
    +.next
    +out
    +
    +# Nuxt.js build / generate output
    +.nuxt
    dist
    +
    +# Gatsby files
    +.cache/
    +# Comment in the public line in if your project uses Gatsby and not Next.js
    +# https://nextjs.org/blog/next-9-1#public-directory-support
    +# public
    +
    +# vuepress build output
    +.vuepress/dist
    +
    +# Serverless directories
    +.serverless/
    +
    +# FuseBox cache
    +.fusebox/
    +
    +# DynamoDB Local files
    +.dynamodb/
    +
    +# TernJS port file
    +.tern-port
    +
    +# Stores VSCode versions used for testing VSCode extensions
    +.vscode-test
    +
    +# yarn v2
    +.yarn/cache
    +.yarn/unplugged
    +.yarn/build-state.yml
    +.yarn/install-state.gz
    +.pnp.*
    +
    +# Project
    dist-ssr
    *.local
    

  4. git add -u

  5. git commit -m 'Setup .gitignore from https://github.com/github/gitignore/blob/master/Node.gitignore'

Add test for src/App.vue

  1. To get 100% reported coverage, we will add test for src/App.vue.
  2. touch tests/unit/App.spec.vue.
  3. Update tests/unit/App.spec.vue.

    diff --git a/tests/unit/App.spec.ts b/tests/unit/App.spec.ts
    new file mode 100644
    index 0000000..b050a5c
    --- /dev/null
    +++ b/tests/unit/App.spec.ts
    @@ -0,0 +1,9 @@
    +import { mount } from '@vue/test-utils'
    +import App from '@/App.vue'
    +
    +describe('App.vue', () => {
    +  it('has header', () => {
    +    const wrapper = mount(App)
    +    expect(wrapper.html()).toMatch('<h1>Hello Vue 3 + TypeScript + Vite</h1>')
    +  })
    +})
    
    1. Run our tests
    $ npm run test
    
    > vite-vue-typescript-starter@0.0.0 test
    > jest
    
     PASS  tests/unit/HelloWorld.spec.ts
     FAIL  tests/unit/App.spec.ts
      ● Test suite failed to run
    
        Jest encountered an unexpected token
    
        Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
    
        Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
    
        By default "node_modules" folder is ignored by transformers.
    
        Here's what you can do:
         • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        https://jestjs.io/docs/configuration
        For information about custom transformations, see:
        https://jestjs.io/docs/code-transformation
    
        Details:
    
        /Users/batiskaf/Development/personal/vue-ts/src/assets/logo.png:1
        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){�PNG
    
        SyntaxError: Invalid or unexpected token
    
          25 |   margin-top: 60px;
          26 | }
        > 27 | </style>
             |                  ^
          28 |
    
          at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1479:14)
          at Object.<anonymous> (src/App.vue:27:18)`
    ...
    

Fix SyntaxError: Invalid or unexpected token error

  1. Luckily there is a clue in error message

    Details:
    
    /Users/batiskaf/Development/personal/vue-ts/src/assets/logo.png:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){�PNG
    

    It may seem weird why Jest complaining about our logo.png but this tells us that we need to update our jest.config.js to enable transforming of *.png files.

  2. We will follow @vue/cli-plugin-unit-jest example and setup jest-transform-stub

  3. Install it npm install --save-dev jest-transform-stub

  4. Update jest.config.js.

diff --git a/jest.config.js b/jest.config.js
index f718135..15a2d43 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -4,6 +4,10 @@ module.exports = {
   testEnvironment: 'jsdom',
   transform: {
     '^.+\\.vue$': 'vue3-jest',
+    // Jest doesn't handle non JavaScript assets by default.
+    // https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-plugin-unit-jest/presets/default/jest-preset.js#L19
+    '.+\\.(css|styl|less|sass|scss|jpg|jpeg|png|svg|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|avif)$':
+      require.resolve('jest-transform-stub'),
   },
   moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue'],
   moduleNameMapper: {

Enter fullscreen mode Exit fullscreen mode
  1. Rerun Jest.

    $ npm run test
    
    > vite-vue-typescript-starter@0.0.0 test
    > jest
    
     PASS  tests/unit/HelloWorld.spec.ts
     PASS  tests/unit/App.spec.ts
    -----------------|---------|----------|---------|---------|-------------------
    File             | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
    -----------------|---------|----------|---------|---------|-------------------
    All files        |     100 |      100 |     100 |     100 |
     src             |     100 |      100 |     100 |     100 |
      App.vue        |     100 |      100 |     100 |     100 |
     src/components  |     100 |      100 |     100 |     100 |
      HelloWorld.vue |     100 |      100 |     100 |     100 |
    -----------------|---------|----------|---------|---------|-------------------
    
    Test Suites: 2 passed, 2 total
    Tests:       2 passed, 2 total
    Snapshots:   0 total
    Time:        5.805 s
    Ran all test suites.
    
  2. git add -u && git add tests/

  3. git commit -m 'add tests/unit/App.spec.ts and install jest-transform-stub'

Links

Project

GitHub logo imomaliev / vue-ts-tailwind

Vite + Vue + TypeScript + TailwindCSS template

Discussion (3)

Collapse
elainemiller profile image
bsreject

sir? where i can contact you? im first time using tailwind css can you help me with simple responsive table only sir?

Collapse
imomaliev profile image
Sardorbek Imomaliev Author

Hi, I think for this question will be best if it is asked on stackoverflow. If you post it here send me a link I will take a look

Collapse
elainemiller profile image
bsreject

thank you for notice me. doing tailwind code now just practice using this code. simple responsive table only. why like this