Vite vue ts tailwind template: Setup Jest coverage and add tests
Tags: vue, typescript, tailwindcss, jest
Published: 2021-08-09 00:19:55

## Enable and setup tests coverage

1. To enable coverage in Jest we need to set [`collectCoverage`](https://jestjs.io/docs/configuration#collectcoverage-boolean) in our configs to `true`.
1. By default, coverage will run on all files. To avoid that, let's [configure Jest](https://jestjs.io/docs/configuration#collectcoveragefrom-array) to collect coverage only on our `src` dir and only on actual code files.
1. Update our `jest.config.js`
    ```diff
    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',
    +  ],
     }
    ```
1. `git add -u`
1. `git commit -m 'enable jest coverage'`
1. Run tests with enabled coverage

    ```console
    $ 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`](https://github.com/imomaliev/vue-ts) template {% link https://dev.to/imomaliev/create-vite-project-460p %} there was initial `.gitignore` file which was created as a part of `vite/vue-ts` scaffold.
1. 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`.

    ```console
    $ 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/
    ```

1. `coverage/` [folder](https://jestjs.io/docs/configuration#coveragedirectory-string) contains generated reports. We should add it to `.gitignore`. To do that we will use [`Node.gitignore`](https://github.com/github/gitignore/blob/master/Node.gitignore) from very helpful `.gitignore` collection [repo by github](https://github.com/github/gitignore).

    {% collapsible Expand .gitignore diff %}

    ```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
    ```

    {% endcollapsible %}

1. `git add -u`
1. `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`.
1. `touch tests/unit/App.spec.vue`.
1. Update `tests/unit/App.spec.vue`.

    ```diff
    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

    ```console
    $ 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

    ```console
    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 `transform`ing of `*.png` files.

1. We will follow [`@vue/cli-plugin-unit-jest`](https://github.com/vuejs/vue-cli/blob/cf1022d4c4921220277e1dc9f9745f8ae12db5b6/packages/%40vue/cli-plugin-unit-jest/presets/default/jest-preset.js#L19) example and setup [`jest-transform-stub`](https://www.npmjs.com/package/jest-transform-stub)
1. Install it `npm install --save-dev jest-transform-stub`
1. Update `jest.config.js`.

```diff
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: {

```

1. Rerun Jest.

    ```diff
    $ 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.
    ```

1. `git add -u && git add tests/`
1. `git commit -m 'add tests/unit/App.spec.ts and install jest-transform-stub'`

## Links

-   https://jestjs.io/docs/configuration#collectcoverage-boolean
-   https://jestjs.io/docs/configuration#collectcoveragefrom-array
-   https://github.com/imomaliev/vue-ts
-   https://jestjs.io/docs/configuration#coveragedirectory-string
-   https://github.com/github/gitignore/blob/master/Node.gitignore
-   https://github.com/github/gitignore/
-   https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-plugin-unit-jest/presets/default/jest-preset.js

## Project

{% github https://github.com/imomaliev/vue-ts-tailwind no-readme %}