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" }]
]
}
Related
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
I have external directory common and I would like to import react components from that directory into web-static. In web-static I am using nextjs.
Currently I having this error:
Module not found: Can't resolve 'react' in '/Users/jakub/Sites/WORK/wilio-web-common/common/src/#vendor/atoms'
I added these lines to next.config.js:
const babeRule = config.module.rules[babelRuleIndex];
if (babeRule && babeRule.test) {
babeRule.test = /\.(web\.)?(tsx|ts|js|mjs|jsx)$/;
if (babeRule.include) {
babeRule.include = [
...babeRule.include,
resolve(__dirname, "../common/src/#vendor"),
];
}
}
config.resolve.alias = {
...config.resolve.alias,
"#vendor": resolve(__dirname, "../common/src/#vendor")
};
My tsconfig.json file:
"paths": {
"#vendor/*": ["../common/src/#vendor/*"]
}
Webpack can resolve these components but can't resolve installed packages in these components.
../common/src/#vendor/atoms/Test.js
Module not found: Can't resolve 'react' in '/Users/user1/Sites/WORK/web-app/common/src/#vendor/atoms'
Do I need to include this directory also in webpacks config.externals? Current nextjs webpack externals
-----
options.isServer: false
[ 'next' ]
-----
-----
options.isServer: true
[ [Function] ]
-----
How can be this done? Thanks for any help
Starting in Next.js 10.1.2, you can use the currently experimental externalDir option in next.config.js:
module.exports = {
experimental: {
externalDir: true,
},
};
Note that for React components to work, I also had to declare the root package.json as a yarn workspace:
{
// ...
"private": true,
"workspaces": ["next-js-directory"],
// ...
}
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 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"
}
I have a unit test for a ReactJs/Typescript project that has a reference to a module called nock.js, and using jest:
import nock from 'nock'
...
afterEach(() => {
nock.cleanAll();
})
When I run the test I get an error in the .cleanAll statement:
TypeError: nock_1.default is not a function
However when I change the import statement to :
var nock = require('nock');
The issue is solved. How can I still use import instead of require ? Is this an issue with the jest configuration? This is the config:
"jest": {
"transform": {
"^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
},
If a module has a default export, you can use:
import nock from 'nock'
But if it doesn't have a default export, you'll need to use:
import * as nock from 'nock'
I met the same exact issue, and fixed it by adding the following config to my tsconfig.json:
{
...
"esModuleInterop": true
...
}