ts-jest cannot resolve tsconfig aliases - javascript

I have a typescript project and I setup aliases in ts.config.json
{
"compilerOptions": {
"paths": {
"#pkg/*": ["./packages/*"],
},
}
}
in my ts files I can shorten my import paths
// example.ts
import {someThing} from '#pkg/mypackage'
it works fine with tsc and vscode can recognize the alias path correctly.
but when I run npm t whitch runs jest it fails
Cannot find module '#pkg/mypackage' from 'example.ts'
jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
transform: {
"^.+\\.tsx?$": "ts-jest",
},
};
I added this to my package.json file
"jest": {
"moduleNameMapper": {
"#pkg/(.*)": "<rootDir>/packages/$1"
}
}
I managed to use pathsToModuleNameMapper, but I had this issue
https://github.com/kulshekhar/ts-jest/issues/2709

I had the same problem, but managed to get it working by using a couple of plugins. I also have some extra matchers at the end for some additional test types.
My Jest-base.config.js has the tsconfig-paths-jest plugin installed and running. This plugin solved my tsconfig path issues.
I use a common base file for common configuration between unit tests and end to end tests, both of which I run via Jest currently.
jest-base.config.ts
const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);
module.exports = {
moduleNameMapper,
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: './',
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/**/*.ts',
'!<rootDir>/**/*.interface.ts',
'!<rootDir>/**/*.mock.ts',
'!<rootDir>/**/*.module.ts',
'!<rootDir>/**/__mock__/*',
'!<rootDir>/src/main.ts'
],
coverageProvider: 'v8',
coverageReporters: [
'clover',
'json',
'lcov',
'text',
'text-summary'
],
resetModules: true,
setupFiles: [
'dotenv/config'
],
// Add the community jest-extended matchers
setupFilesAfterEnv: [
'jest-extended'
],
verbose: false
};
My jest.config.js (for unit tests) will extend my jest-base.config.js to add unit test specific code such as coverage requirements, where to store output for coverage etc.
jest.config.js
const JestBaseConfiguration = require('./jest-base.config');
module.exports = Object.assign(JestBaseConfiguration, {
moduleFileExtensions: ['js', 'json', 'ts'],
testRegex: '.e2e-spec.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest'
},
...

Related

Eslint doesn't respect jsconfig paths

I have my express.js project in monorepo. I want to add custom path alias to it.
The directory structure is:
./
server/
----> jsconfig.json
----> .eslintrc.js
----> src/
--------> index.js
--------> modules/auth
-------------> auth.controller.js
jsconfig.json
{
"compilerOptions": {
"module": "ES6",
"baseUrl": "./",
"paths": {
"#modules/*": [
"src/modules/*"
]
}
},
"exclude": ["node_modules"]
}
.eslintrc.js
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'airbnb-base',
],
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {
'no-console': 'error',
'no-debugger': 'error',
},
settings: {
'import/resolver': {
alias: {
map: [
['#modules/*', 'src/modules/*'],
],
extensions: ['.js', '.json'],
},
},
},
};
Simply, I just tried to import auth controller in my index.js file.
import authRoutes from '#modules/auth/auth.routes';
but I get the following error: Unable to resolve path to module '#modules/auth/auth.controller' .eslint import/no-unresolved
please, don't suggest to turn off the rule.
I've alreadyy tried eslint-import-resolver-jsconfig, but I got Cannot resolve jsConfig, SyntaxError } on 150.
Because I used monorepo, there was a problem for ESLint or even lint-staged.
So now I have only one project per repository and:
Added custom paths in jsconfig.json:
"paths": {
"#modules/*": [
"./src/modules/*"
]
}
Installed eslint-import-resolver-jsconfig and added the following configuration to the eslint.json:
"extends": [
"airbnb-base",
"eslint:recommended"
],
"plugins": ["import"],
"settings": {
"import/resolver": {
"jsconfig": {
"config": "jsconfig.json"
}
}
}
Installed the Babel plugin babel-plugin-module-resolver and added the following settings to the .babelrc:
"plugins": [
[
"module-resolver",
{
"alias": {
"#modules": "./src/modules"
}
}
]
]
But, again: This only works if you have one project per repository and all your configuration files (.*rc, package.json, etc) are in the root level.
To achieve the above I use the module-alias package.
After installing it as a normal dependency, npm i --save module-alias, add the following to your package.json:
"_moduleAliases": {
"#modules": "./src/modules"
}
That will basically define the mappings for all the aliases you want to define.
To make it work, you will now need to import the following on top of your application under index.js:
require("module-alias/register"); // If using commonJS
// or
import "module-alias/register"; // If transpiling es6
You are now all set and should be able to import your files with absolute paths looking as:
const authRoutes = require("#modules/auth/auth.routes")
// or
import authRoutes from "#modules/auth/auth.routes";
In case eslint still flags the unresolved path, you may need to update your jsconfig.json or tsconfig.json to contain the below:
"paths": {
"#modules/*": ["src/modules/*"]
}
You can find the package documentation and read more about its usage here.

Babel module resolver not working with react-native

My babel module resolver is not working with React-Native (neither does intellij in VScode)
Here, Is my babel config
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};
And jsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#assets": ["./assets"],
"#modules": ["./modules"],
"#config": ["./config"],
"#utils": ["./utils"]
}
}
}
I changed import for one of my files and this is the error I get when I executed the build command from Xcode
Error: Error loading assets JSON from Metro. Ensure you've followed
all expo-updates installation steps correctly. Unable to resolve
module ../../modules/store/components/Filters from
src/utils/Router.js:
None of these files exist:
Where I imported the file like this
import Filters from '#modules/store/components/Filters';
I had the same problem, I just removed the '#' from my aliases and it seems working fine now.
Here is my babel.config.js
module.exports = function (api) { ■ File is a CommonJS module; it may be converted to an ES6 module.
api.cache(true);
return {
presets: ["babel-preset-expo"],
plugins: [
[
require.resolve("babel-plugin-module-resolver"),
{
root: ["./src/"],
alias: {
// define aliases to shorten the import paths
components: "./src/components",
containers: "./src/containers",
contexts: "./src/contexts",
interfaces: "./src/interfaces",
organizer: "./src/screens/organizer",
screens: "./src/screens",
},
extensions: [".js", ".jsx", ".tsx", ".ios.js", ".android.js"],
},
],
],
};
};
Try resetting the cache, if above suggested answers don't work
react-native start --reset-cache
This worked for me. For more info see here
Change your module-resolver's root to ['./src/']:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src/'], // <-- here ✅
alias: {
'#assets': './src/assets',
'#modules': './src/modules',
'#config': './src/config',
'#utils': './src/utils',
},
},
],
],
};

Absolute imports not working in jest tests (*.test.ts files) [duplicate]

I am setting a configuration to run my tests in a create-react-app + typescript app (from which I have ejected). I am using jest + enzyme. In my tsconfig.json I have set baseUrl='./src' so I can use absolute paths when I import modules. For example this is a typical import statement in one of my files:
import LayoutFlexBoxItem from 'framework/components/ui/LayoutFlexBoxItem';
You can see that the path is absolute (from /src folder) and not relative.
This works fine when I run in debug mode ( yarn start )
But when I run my test ( yarn test ), I get this error:
Cannot find module 'framework/components/Navigation' from 'index.tsx'
So it looks like jest is not able to resolve this absolute path although I have set it up in my tsconfig.json. This is my tsconfig.json:
{
"compilerOptions": {
"outDir": "dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"baseUrl": "./src"
},
"exclude": [
"node_modules",
"build",
"dist",
"config",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}
Now I can see that there is a generated tsconfig.test.json at the root of my project. This is the ts configuration used for test. And here is its content:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "commonjs"
}
}
As you can see the "module" is commonjs here whereas in the default configuration it is esnext. Could this be one reason?
Has any one been able to unit test his typescript project with Jest and absolute path? or is this a known bug? Since I have ejected from default configuration, are there some settings to put in my webpack configuration?
Thanks for your input and suggestion.
I was struggling with the same problem and actually it turns out that a simple change seems to do the trick.
I just updated the moduleDirectories field in jest.config.js.
Before
moduleDirectories: ['node_modules']
After
moduleDirectories: ['node_modules', 'src']
As many here pointed out moduleNameMapper in jest.config.js needs to define paths specified in tsconfig.json. For example, if you have paths in tsconfig.json defined as follows
// tsconfig.json
{
...
"baseUrl": "src",
"paths": {
"#alias/*": [ 'path/to/alias/*' ]
}
...
}
then your jest.config.js needs to provide those paths in moduleNameMapper in the following format:
// jest.config.js
module.exports = {
'roots': [
'<rootDir>/src'
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'moduleNameMapper': {
'#alias/(.*)': '<rootDir>/src/path/to/alias/$1'
}
};
Having that we can improve our jest.config.js to convert paths defined in tsconfig.json automatically. Here is a Gist code snippet for that:
// jest.config.js
function makeModuleNameMapper(srcPath, tsconfigPath) {
// Get paths from tsconfig
const {paths} = require(tsconfigPath).compilerOptions;
const aliases = {};
// Iterate over paths and convert them into moduleNameMapper format
Object.keys(paths).forEach((item) => {
const key = item.replace('/*', '/(.*)');
const path = paths[item][0].replace('/*', '/$1');
aliases[key] = srcPath + '/' + path;
});
return aliases;
}
const TS_CONFIG_PATH = './tsconfig.json';
const SRC_PATH = '<rootDir>/src';
module.exports = {
'roots': [
SRC_PATH
],
'transform': {
'^.+\\.tsx?$': 'ts-jest'
},
'moduleNameMapper': makeModuleNameMapper(SRC_PATH, TS_CONFIG_PATH)
};
Here is how I got moduleNameMapper working.
With the below config in my tsconfig:
"paths": {
"#App/*": [
"src/*"
],
"#Shared/*": [
"src/Shared/*"
]
},
Here's the moduleNameMapper:
"moduleNameMapper": {
"#App/(.*)": "<rootDir>/src/$1",
"#Shared/(.*)": "<rootDir>/src/Shared/$1"
}
Add this following section in your package.json. after you made the changes don't forget to restart your test watchers.
"jest": {
"moduleDirectories": [
"node_modules",
"src"
],
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"roots": [
"src"
],
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node",
"moduleNameMapper": {
"src/(.*)": "<rootDir>/src/$1"
}
}
For me, I just needed to add
"modulePaths": ["<rootDir>/src"],
to my jest.config.js file.
Following answer to modify moduleDirectories resulted in this error:
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
Using:
modulePaths: ["node_modules", "<rootDir>/src"],
From reading the docs it appears that this a list of additional directories and so node_modules is unnecessary.
For those using an absolute path but not using named mappings, this worked for me:
# jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
}
}
# jest.config.js
const config = {
moduleDirectories: ['node_modules', '<rootDir>'],
};
Solution using the best practice
This error occurs because of using absolute paths in the import statements of our TypeScript/Nest.js/Angular projects while using Jest. Fixing it with moduleDirectories and moduleNameMapper options may solve your problem temporarily but it creates issues with other packages such as this TypeORM issue. Also, the creator of the Nest.js framework suggests that using absolute paths is a bad practice. TypeScript's official documentation recommends using relative paths for our own modules. There's also an ESLint rule that explains why absolute paths should be avoided.
Absolute path vs Relative path
import statement with absolute path looks like:
import { AuthService } from 'src/auth/auth.service'
import statement with relative path looks like:
import { AuthService } from '../auth/auth.service'
VS Code Setting
VS Code by default uses absolute path as shown above, when we auto-import using code completion or Command/Ctrl + .. We need to change this default setting to use relative paths.
Go to VS Code settings and search for a setting: Import Module Specifier. Change it from shortest to relative.
Now from here on, VS Code will automatically import using the relative paths.
Fixing imports in the project
Now in the project files, look for the absolute paths in the imports that look like the example above and delete them. You will see errors for the packages that you deleted. Simply use the auto-import suggestions and import them back. This time they will be imported using the relative paths. This step may be tedious depending on the size of your project but it's worth it in the long run.
Hope that works out! Cheers!
ts-jest can resolve this problem perfectly!
https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping#jest-config-with-helper
just modify jest.config.js like this:
const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
// preset is optional, you don't need it in case you use babel preset typescript
preset: 'ts-jest',
// note this prefix option
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, /* { prefix: '<rootDir>/' } */)
}
Here is what worked for me:
npm i -D jest typescript
npm i -D ts-jest #types/jest
npx ts-jest config:init
Then in jest.config.js, here's my setup
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
modulePaths: ["node_modules", "<rootDir>/src"],
};
in my case, I do not have any paths in tsconfig.json but I have baseUrl set to src
If you have intalled ts-jest you can use an util function called pathsToModuleNameMapper to convert the path inside tsconfig.json to your jest.config file:
My jest.config.js file:
const { join } = require('path');
const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig.json')
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
rootDir: __dirname,
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
setupFiles: ['<rootDir>/src/config/env.ts'],
collectCoverageFrom: ["<rootDir>/src/modules/**/*UseCase.ts"],
coverageProvider: "v8",
coverageThreshold: {
global: {
lines: 40
}
},
bail: true,
clearMocks: true,
displayName: 'unit-tests',
testMatch: ["<rootDir>/src/modules/**/*.spec.ts"],
preset: 'ts-jest',
testEnvironment: 'node',
modulePaths: ["<rootDir>/src"],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
prefix: join('<rootDir>', compilerOptions.baseUrl)
})
};
I've using React with Typescript, I removed react-scripts-ts test --env=jsdom from npm test and added jest --watch as my default test, after I added jest.config.js to my project following these instructions https://basarat.gitbooks.io/typescript/docs/testing/jest.html
and I used the the configuration mentioned by #Antonie Laffargue (add/edit property moduleDirectories: ['node_modules', 'src']), it works perfectly.
I had a similar problem. I hope this could help to spare time for some of you.
My problem:
using create-react-app with typescript
using absolute paths (src/MyComp) to import components inside other components (e.g. App.tsx)
it was working on compile/run/build
it was not working on test
I found that the error was due to a different value of the NODE_PATH. So I set it on tests run.
I recreated the issue and the fix in here: https://github.com/alessandrodeste/...
I'm not sure if this could bring side effects on tests. Let me know if you have feedback ;)
You probably want moduleNameMapper feature of jest config.
It will map your custom import namespaces to real module locations.
see official documentation here:
https://facebook.github.io/jest/docs/en/configuration.html#modulenamemapper-object-string-string
If this happens to you in monorepo here's what fixed the problem for me:
Inside jest.config.js
roots: ["<rootDir>packages"],
moduleNameMapper: {
'#monopre/(.+)$': '<rootDir>packages/$1/src',
},
Assuming you have in tsconfig.json
"paths": {
"#monopre/*": ["packages/*/src"],
}
Adding the following to my jest config in package.json resolved this problem for me.
"moduleDirectories": [
"node_modules",
"src"
]
I use "baseUrl": "./" without any aliases in tsconfig.json
moduleDirectories: ['node_modules', '<rootDir>'] in jest.config.ts worked for me.
Now I can import local modules e.g import { Hello } from "src/modules/hello" without any problems.
jest.config.ts
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/
export default {
clearMocks: true,
collectCoverageFrom: ['**/*.(t|j)s'],
coverageDirectory: 'coverage',
coverageProvider: 'v8',
moduleDirectories: ['node_modules', '<rootDir>'],
moduleFileExtensions: ['js', 'json', 'ts'],
roots: ['src', 'test'],
setupFiles: ['dotenv/config'],
testRegex: ['.*\\.spec\\.ts$'],
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
};
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"esModuleInterop": true,
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"resolveJsonModule": true
},
"include": ["src/**/*", "src/**/*.json", "test/**/*"]
}
Using Svelte Kit, my solution was:
import { readFileSync } from 'fs';
import pkg from 'ts-jest/utils/index.js';
const { pathsToModuleNameMapper } = pkg;
const { compilerOptions } = JSON.parse(readFileSync('./tsconfig.json'))
export default {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/**/*.test.ts'],
testPathIgnorePatterns: ['/node_modules/'],
coverageDirectory: './coverage',
coveragePathIgnorePatterns: ['node_modules'],
globals: { 'ts-jest': { diagnostics: false } },
transform: {},
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
}
I had the same problem using StitchesJS, the module was not found, the solution was to put this in my jest.config.js
moduleNameMapper: {
"stitches.config": "<rootDir>/node_modules/#stitches/react/dist/index.cjs"}
You can adapt according to the module you want.
If you have a monorepo where each project has its own tsconfig.json that extends from the base (root) tsconfig.json, and each project has its own jest.config.js, and you launch tests from the project root, you should add your moduleNameMapper to the jest.config.js in the project root.
Eg.
backend/
- tsconfig.json
- jest.config.js
frontend/
- tsconfig.json
- jest.config.js
/
- tsconfig.json
- jest.config.js
And your problem is in the jest tests frontend/ and it has a tsconfig like:
{
"compilerOptions": {
"jsx": "react-native",
"paths": {
"src/*": ["client/src/*"]
},
"noEmit": true
},
"extends": "../tsconfig.json"
}
Then adding this to the root jest.config should fix the issue:
moduleNameMapper: {
'src/(.*)': '<rootDir>/client/src/$1',
},
So in total, something like:
module.exports = {
testEnvironment: 'node',
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
testPathIgnorePatterns: ['cdk.out/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
modulePathIgnorePatterns: ['tests'],
globals: {
'ts-jest': {
isolatedModules: true,
},
},
moduleNameMapper: {
'src/(.*)': '<rootDir>/client/src/$1',
},
};
Sort of obvious, but adding this answer since I didn't see this case in the other answers, and monorepos are still a thing :)
Kind of an old thread but recently, on top of the other suggestions of adding the paths on "moduleNameMapper": on jest.config.js and "paths": on tsconfig.json, I also had to include my test folder so the compiler could recognize it.
So on tsconfig.json, add:
...
"include": ["src", "__tests__"],
...
Hope it helps on someone googling for it 😉

Jest - cannot find module

I have the following test:
jest.mock('#my-company/my-package/dist/browser');
import { broadcast } from '#my-company/my-package/dist/browser';
...
The file it is importing looks something like this within the node_modules folder:
import someFunction from '#my-company/some-other-package';
...
This is throwing the following error message when I run the test:
Cannot find module '#my-company/some-other-package' from 'browser.js'
Why would I be getting this error?
I have been going through my jest config file and can't spot anything that might be wrong. Here is the config file:
module.exports = {
testPathIgnorePatterns: [
'/node_modules/',
'/bower_components/',
'/cypress/',
'/test/', // test directory contains mocha and chai tests for now
],
transform: {
'.(js|jsx)': '#sucrase/jest-plugin',
},
transformIgnorePatterns: [`node_modules/(?!#my-company/my-package)`],
resolver: '#my-company/jest-bower-resolver',
setupFilesAfterEnv: ['<rootDir>/test/setup-tests.js'],
moduleDirectories: ['node_modules', 'bower_components', "<rootDir>"],
collectCoverageFrom: [
'**/*.{js,jsx}',
'!**/*.spec.js',
'!**/test/**',
'!**/test-jest/**',
'!**/cypress/**',
'!**/coverage/**',
'!**/node_modules/**',
'!**/bower_components/**',
'!**/public/**',
],
coverageDirectory: '<rootDir>/coverage/',
};
It is important to note that the package #my-company/my-package must be added to transformIgnorePatterns part of the config otherwise it won't be transpiled
Thanks

Jest - No output of test results

I've been having difficulties with Jest ever since I tried to begin using it. No tests I try to run and with what options I try to pass Jest, I never get the 'Pass' / 'Fail' output results in the console.
Jest always just outputs 'Done'
Using the 'Nuxt CLI' there is a default test written as:
import { mount } from '#vue/test-utils'
import Logo from '#/components/Logo.vue'
describe('Logo', () => {
test('is a Vue instance', () => {
const wrapper = mount(Logo)
expect(wrapper.isVueInstance()).toBeTruthy()
})
})
So far I have tried:
yarn test
yarn test --verbose
yarn test --watch
yarn test --watchAll
yarn test --no-watchmen
Every single time, the result is as follows:
yarn run v1.21.1
$ jest
Done in 0.72s.
Current jest.config.js:
module.exports = {
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js'
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest'
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue'
]
}
This seems to be the default config for Nuxt.
Any help would be appreciated
So I figured it out (kind-of).
My tests run fine with the following:
yarn test --no-watchman
I can't figure out why watchman is causing me so many issues but this does seem to help.
More Info:
https://github.com/facebook/jest/issues/2219
Jest looks for files ending with .spec.js or .test.js file formats. Try putting your test in a file ending with .spec.js or .test.js file. Also you can configure jest, using jest.config.js file.
One such example of using jest.config.js file is
const path = require('path')
module.exports = {
rootDir: path.resolve(__dirname),
moduleFileExtensions: [
'js',
'json',
'vue',
'ts'
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
transform: {
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest",
"^.+\\.(js|jsx)?$": "<rootDir>/node_modules/babel-jest",
"^.+\\.ts$": "<rootDir>/node_modules/ts-jest"
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
snapshotSerializers: [
"jest-serializer-vue"
],
testEnvironment: "jsdom",
setupFiles: [
"<rootDir>/globals.js"
]
}

Categories