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.
jest.mock('../src/service', () => require('./__mocks__/request'));
This has worked for me
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With