Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move '__mocks__' folder in Jest to /test?

I have started using mocks in Jest for testing my NodeJS app and they're working nice, but it would make more sense to move __mocks__ folder to /test folder so everything related to tests is there instead of mixing files in /src.

Is it possible in some way? I cannot find it anywhere in Jest docs.

like image 556
Marek Urbanowicz Avatar asked Jul 12 '18 10:07

Marek Urbanowicz


2 Answers

jest.mock('../src/service', () => require('./__mocks__/request'));

This has worked for me

like image 168
ymehenni Avatar answered Oct 07 '22 18:10

ymehenni


In my package.json i have some jest config

"jest": {
    "preset": "jest-preset-angular",
    "transform": {
      "^.+\\.js$": "babel-jest",
      "^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js"
    },
    "transformIgnorePatterns": [
      "node_modules/babel-runtime"
    ],
    "setupTestFrameworkScriptFile": "<rootDir>/src/__tests__/setupJest.ts",
    "moduleNameMapper": {
      "mockData": "<rootDir>/src/__tests__/data",
      "mockService": "<rootDir>/src/__tests__/services"
    },
    "testResultsProcessor": "jest-junit",
    "testMatch": [
      "**/?(*.)(spec).ts?(x)"
    ]
  },
  "jest-junit": {
    "suiteName": "jest tests",
    "output": "./reports/tests/TESTS-junit.xml",
    "classNameTemplate": "{classname}-{title}",
    "titleTemplate": "{classname}-{title}",
    "usePathForSuiteName": "true"
  }

The "moduleNameMapper" part is what you need, I added these parts after my devDependencies. You can also create a config file elsewhere.

https://jestjs.io/docs/en/configuration

EDIT:

You have to modify these path :

"mockData": "<rootDir>/src/__tests__/data",
"mockService": "<rootDir>/src/__tests__/services"

So if you want Mock outside src folder you can replace my conf by :

"mockData": "<rootDir>/__tests__/data",
"mockService": "<rootDir>/__tests__/services"
like image 40
Nolyurn Avatar answered Oct 07 '22 20:10

Nolyurn