3

I want to use a helper object/function in a Jest test with Vue test-utils, where I have a tests folder on my project root.

unitMocks.js in tests/unit/unitMocks.js

export const mockComputed = {
  products() {
    return [1, 2, 3];
  },
  activities() {
    return [4, 5, 6];
  },
  ....
};

export const mockGetterProduct = () => {
...

Dashboard.spec.js in tests/unit/views/

import Dashboard from "@/views/Dashboard.vue";
import { mockComputed } from "../unitMocks.js";
...

describe("Dashboard.vue", () => {
...

To import this, I want to avoid using a relative path (../unitMocks.js) so I was wondering how to access the relative root path.

I'm aware of the babel root import plugin and I also tried to modify the webpack alias of my vue.config.js:

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        tests: "tests/"
      }
    }
  },
  ...

..but my test still won't find that file when I import it.

Isn't there a native way of accessing the root path (like @ for src)? Is this related to Webpack or Babel?

1
  • In webpack.base.conf.js, you can add another symbol that resolves to tests folder. You should add it inside resolve: {alias: {}} Commented Oct 19, 2018 at 14:36

1 Answer 1

3

Webpack's resolve.alias can be accomplished in Jest configuration with moduleNameMapper. Specifically, to add a tests alias mapped to <rootDir>/tests/, add the following to jest.config.js:

moduleNameMapper: {
  '^tests/(.*)$': '<rootDir>/tests/$1',
},

Then, you could import tests/unit/foo.json from your test scripts like this:

// In tests/x/y/z/example.spec.js
import foo from 'tests/unit/foo.json';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.