I have set up my jest to allow static files after following their documentation on how to do so, but I still recieve the following error.
How can I can it to pass and create a snapshot.
Terminal Error
FAIL src/components/Splash/Splash.test.js
● Test suite failed to run
/var/www/com/src/components/shared/logo/_Logo.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.logo {
^
SyntaxError: Unexpected token .
3 |
4 |
> 5 | import logo from './_Logo.css';
6 | import * as font from '../font/fontello.css';
Splash.test.js
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import Splash from './Splash';
it('Splash page is rendered', () => {
const result = shallow(
<Splash />,
);
expect(shallowToJson(result)).toMatchSnapshot();
});
Jest Config
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"setupTestFrameworkScriptFile": "./node_modules/jest-enzyme/lib/index.js",
"moduleFileExtensions": [
"js"
],
"moduleDirectories": [
"node_modules"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/app/"
],
"moduleNameMapper": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "identity-obj-proxy"
}
},
"transform": {
"^.+\\.js$": "babel-jest"
}
}
It may work who use create-react-app from feb 2018.
I partially followed the docs jest webpack to make it work.
Also found out the moduleNameMapper cannot be overriden in package.json but in jest.config.js it does the trick.
Unfortunately i havent found any docs about why it does but here is my answer.
Here is my jest.config.js:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
I added to devDependencies identity-obj-proxy
There is a small mistake: moduleNameMapper: {moduleNameMapper{}} should just be moduleNameMapper:{}
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "identity-obj-proxy"
}
Related
I am going to test below component
WalletButton.jsx
import React from 'react';
import { WalletDialogButton } from "#solana/wallet-adapter-material-ui";
function WalletButton() {
return (
<WalletDialogButton>
{"CONNECT"}
</WalletDialogButton>
);
}
export default WalletButton;
The test case is below:
wallet-button.test.js
import {shallow} from "enzyme"
import React from 'react'
import WalletButton from "./WalletButton";
it('render WalletButton Component', () => {
expect(shallow(<WalletButton/>)).toMatchSnapshot();
})
When I run npm test, it shows error
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
/Users/CCCC/Desktop/SourceTree/my-project/node_modules/#solana/wallet-adapter-material-ui/lib/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './useWalletDialog';
I attempt to add
transformIgnorePatterns: [
"node_modules/(?!#solana/wallet-adapter-material-ui)",
]
in jest.config.js but still not working.
How to fix it?
jest.config.js
module.exports = {
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
"\\.(css|scss)$": "identity-obj-proxy",
},
transform: {
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(png|jpg|svg|ttf|woff|woff2)$": "jest-transform-stub",
},
transformIgnorePatterns: [
"node_modules/(?!#solana/wallet-adapter-material-ui)",
],
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
snapshotSerializers: ["enzyme-to-json/serializer"],
};
Update 1
babelrc
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", { "runtime": "automatic" }]
]
}
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.
I am new to Jest. I'm trying to run it with the most basic test:
//App-test.js
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
But I keep getting the Error: ● Test suite failed to run
TypeError: Cannot read property 'createAnimatedComponent' of undefined
at Object.<anonymous> (node_modules/react-native-screens/lib/commonjs/index.js:27:23)
at Object.<anonymous> (node_modules/react-navigation-tabs/lib/commonjs/navigato/createBottomTabNavigator.tsx:10:1)
My jest config in my package.json looks like this:
"jest": {
"preset": "react-native",
"globals": {
"__DEV__": true
},
"transformIgnorePatterns": [
"node_modules/(?!react-native-screens|react-navigation-tabs)/",
"node_modules/(?!react-native-payfort-sdk|react-native|Hacktor|react-native-button|react-navigation)/"
],
"haste": {
"defaultPlatform": "android",
"platforms": [
"android",
"ios"
]
}
}
and my babel.config.js looks like this:
// babel.config.js
module.exports = function(api) {
api.cache(true);
const presets = [
[
'#babel/preset-env',
{
modules: 'auto',
useBuiltIns: 'entry'
}
],
'#babel/react',
'#babel/preset-flow'
];
const plugins = [
'#babel/plugin-transform-flow-strip-types',
'#babel/plugin-proposal-class-properties',
'#babel/transform-runtime',
'add-module-exports',
];
return {
presets,
plugins
};
};
I don't know what I can do anymore. My code is so full because with the most basic settings I was getting every error possible. I'm also running a basic addition test which looks like that:
const functions = require('./functions');
test('Adds 2+2 to equal 4', ()=> {
expect(functions.add(2,2)).toBe(4);
});
which works just fine.
EDIT:
I redid TransformIgnorePatterns like so:
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation|#react-native-community|#react-navigation/.*)"
],
And the Error is still this:
● Test suite failed to run
TypeError: Cannot read property 'createAnimatedComponent' of undefined
at Object.<anonymous> (node_modules/react-native-screens/lib/commonjs/index.js:27:23)
at Object.<anonymous> (node_modules/react-navigation-tabs/lib/commonjs/navigators/createBottomTabNavigator.tsx:10:1)
can you try this:
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation|#react-native-community|#react-navigation/.*)"
],
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"
]
}
I had Jest tests working under Quasar version 0.14. Currently some simple tests and all snapshot-tests pass but for some tests I keep getting:
1.
console.error node_modules/vue/dist/vue.common.js:593
[Vue warn]: Error in config.errorHandler: "TypeError: Cannot read property 'form' of undefined"
and 2:
console.error node_modules/vue/dist/vue.common.js:1743
TypeError: Cannot read property 'getters' of undefined
and 3:
console.error node_modules/vue/dist/vue.common.js:593
[Vue warn]: Unknown custom element: <q-page-sticky> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
1 and 2 seem to relate to Jest not recognizing a $v.form and the vuex store within the components.
Any suggestions/ best practices how to get this working? I followed along this, and have these settings:
.babelrc:
{
"presets": [
[ "env", {"modules": false} ],
"stage-2"
],
"plugins": ["transform-runtime"],
"comments": false,
"env": {
"test": {
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"module-resolver",
{
"root": [
"./src"
],
"alias": {
"quasar": "quasar-framework/dist/quasar.mat.esm.js",
"^vue$": "vue/dist/vue.common.js"
}
}
]
]
}
}
}
within package.json:
"jest": {
"testMatch": [
"<rootDir>/src/**/?(*.)(spec).js?(x)"
],
"testPathIgnorePatterns": [
"<rootDir>/src/e2e/"
],
"moduleNameMapper": {
"src/components/([^\\.]*).vue$": "<rootDir>/src/components/$1.vue",
"src/components/([^\\.]*)$": "<rootDir>/src/components/$1.js",
"^vue$": "vue/dist/vue.common.js",
"src/([^\\.]*)$": "<rootDir>/src/$1.js",
"src/([^\\.]*).vue$": "<rootDir>/src/$1.vue",
"(.*)/(.*).vue$": "$1/$2.vue",
"(.*)/(.*)/(.*).vue$": "$1/$2/$3.vue"
},
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"collectCoverageFrom": [
"**/*.{vue}"
],
"coverageDirectory": "<rootDir>/src/components/coverage",
"transformIgnorePatterns": [
"node_modules/core-js",
"node_modules/babel-runtime",
"node_modules/lodash",
"node_modules/vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
]
},
1. The Problem
Your 3rd error occurred because Jest doesn't know what a <q-page-sticky> is. You have to tell it explicitly.
[Vue warn]: Unknown custom element: <q-page-sticky> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
2. The Solution
Its as simple as telling Vue what 'Vuex' is, or what 'vue-router' is. You are probably already familiar with this. The only difference is that we have to use localVue here in the testing environment.
import { shallowMount, createLocalVue } from "#vue/test-utils";
import MyComponent from "#/components/MyComponent";
// I see that you already alias "quasar" in your .babelrc,
// otherwise replace "quasar" with "quasar-framework/dist/quasar.mat.esm.js"
import Quasar, { q-page-sticky } from "quasar";
// or if you are using a lot of Quasar components then do
// import Quasar, * as All from "quasar";
describe("Something Something", () => {
const localVue = createLocalVue();
localVue.use(Quasar, { components: ["q-page-sticky"]});
// or if you are using a lot of Quasar components then do
// localVue.use(Quasar, { components: All, directives: All, plugins: All });
const wrapper = shallowMount(MyComponent, {
localVue,
});
it("works", () => {
expect(wrapper.isVueInstance()).toBe(true);
});
})
3. Reference
The above is a general solution and can be used not just with Quasar framework. You can checkout the following official vue-test-util docs for more information.
Using with Vue Router
Using with Vuex
I had the same warnings (1 and 2). For me, it was using the wrong mount. I used Vue's mount function instead of the one in #vue/test-utils. I don't have the explanation why it works now, but that was it for me.