DEV Community

Jur de Vries
Jur de Vries

Posted on • Originally published at thecodingartist.com

Jest unit tests location in vue

I like doing test driven development in vue and jest. After doing this for a while I noticed that I don't like the fact that the unit tests live in their own directory apart from the implementation files: I always need some time to find them if I want to work on a component. Why not place the test files next to the component and javascript files as shown in the following directory listing?

- components
    - HelloWorld.spec.js
    - HelloWorld.vue
    - Home.spec.js 
    - Home.vue
- utils

As you can see it is very easy to find the test file and there is no confusion between test files and normal files due to the naming convention of tests (*.spec.js).

So how could we achieve this? It is very simple. We need to change the testMatch configuration of jest. When you created your project using the vue-cli and added jest as the unit testing framework, you will have a jest config file in the root of your project:

// jest.config.js
module.exports = {
  preset: '@vue/cli-plugin-unit-jest'
}

The only thing you have to do is to add the proper textMatch entry to this file:

module.exports = {
  preset: '@vue/cli-plugin-unit-jest',
  testMatch: [
    "**/src/**/*.spec.[jt]s?(x)",
  ]
}

When you now run jest, the test files next to the javascript files will be recognized. You will have to move all your tests next to the components, because with the new setting jest will ignore tests in the tests/unit directory.

How to find these settings?

I found out about this setting by examining the jest config documentation. I also had a look in the initial config by running:

npx jest --showConfig

In the output I saw the initial configuration:

 "testMatch": [
    "**/tests/unit/**/*.spec.[jt]s?(x)",
    "**/__tests__/*.[jt]s?(x)"
  ],

I copied this and just rewrote the first pattern in order to match files in the src directory. As I never use the __tests__ directory I simply deleted this line in order to have no confusion where the tests should be placed.

Top comments (0)