Tests fail to run on React Native - react-native

My babel.config.js is:
module.exports = {
presets: [
'module:metro-react-native-babel-preset'
]
};
When I run npm test I get:
Test suite failed to run
[BABEL] unknown: Preset /* your preset / requires a filename to be set when babel is called directly,
babel.transform(code, { filename: 'file.ts', presets: [/ your preset */] });
See https://babeljs.io/docs/en/options#filename for more information.
If I change config file to:
module.exports = {
presets: [
'react-native'
]
}
then all tests run.
My question: can I change it? What is the difference between both?
Thank you!

Related

The debugger adapter not works after vsce package

I developed a debug extension which uses an external js debugger adapter. I put the js file to the bin directory looks like this.
rootDir
--bin
----adapter.js
And I used it like this in my development environment.
{
"label": "ThingIO Debugger",
"program": "./bin/adapter.js",
"runtime": "node",
"type": "thingio-debug"
}
The code works well in my development mode, but when I packaged it to a .vsix file and install to another machine, it failed immediately.
The webpack file is below
//#ts-check
'use strict';
const path = require('path');
//#ts-check
/** #typedef {import('webpack').Configuration} WebpackConfig **/
/** #type WebpackConfig */
const extensionConfig = {
target: 'node', // vscode extensions run in a Node.js-context πŸ“– -> https://webpack.js.org/configuration/node/
mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
entry: './src/extension.ts', // the entry point of this extension, πŸ“– -> https://webpack.js.org/configuration/entry-context/
output: {
// the bundle is stored in the 'dist' folder (check package.json), πŸ“– -> https://webpack.js.org/configuration/output/
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
libraryTarget: 'commonjs2'
},
externals: {
vscode: 'commonjs vscode' // the vscode-module is created on-the-fly and must be excluded. Add other modules that cannot be webpack'ed, πŸ“– -> https://webpack.js.org/configuration/externals/
// modules added here also need to be added in the .vscodeignore file
},
resolve: {
// support reading TypeScript and JavaScript files, πŸ“– -> https://github.com/TypeStrong/ts-loader
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader'
}
]
}
]
},
devtool: 'nosources-source-map',
infrastructureLogging: {
level: "log", // enables logging required for problem matchers
},
};
module.exports = [ extensionConfig ];
And the vscode:prepublish command is webpack --mode production --devtool hidden-source-map
I think it looks like the debugger adapter program is not found. So I checked the ~/.vscode/extensions, and the adapter js file exists in the right path.
Now I'm very confused about what wrong is with the extension. Maybe the path is wrong or the webpack did not compile the right file in some situation?
Can anyone give some solution or suggestion about this?

Jest Unexpected token 'export' when using d3

I have read many of the questions similar to mine, but none seem to fix my issue. I am using Vue3, TypeScript, Jest, and D3 v7. When I try to import * as d3 from "d3"; I get this error in my tests:
({"Object.<anonymous>":
function(module,exports,require,__dirname,__filename,global,jest)
{export * from "d3-array";
This error also occurs when I import d3 as such
import { BaseType, Selection, Transition, select } from "d3";
I have tried updating my jest config's transformIgnorePatterns property to read but this doesn't work either:
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!d3-(array))",
]
Could someone explain to me the piece I am missing here? Also below is my entire jest.config.js file
module.exports = {
collectCoverageFrom: [
"**/src/**.ts",
"**/src/**/**.ts",
"!**/dist/**",
"!**/node_modules/**",
"!**/public/**"
],
errorOnDeprecated: true,
preset: "#vue/cli-plugin-unit-jest/presets/typescript",
testMatch: ["**/*.spec.ts", "!**/node_modules/**"],
testPathIgnorePatterns: ["<rootDir>/dist/", "<rootDir>/node_modules/"],
"modulePaths": [
"<rootDir>"
],
transformIgnorePatterns: [
"<rootDir>/node_modules/(?!d3-(array))",
],
transform: {
"^.+\\.ts": "ts-jest",
"^.+\\.vue$": "vue-jest",
},
};
A quick fix is to use the minified d3 build, which is already transpiled. Either import the minified build directly:
import * as d3 from 'd3/dist/d3.min'
demo 1
Or use a Jest config to map d3 to the minified build:
// jest.config.js
module.exports = {
moduleNameMapper: {
'^d3$': '<rootDir>/node_modules/d3/dist/d3.min.js',
},
}
demo 2
If that's not an option, you can configure Jest to transpile d3 (and its dependencies that also require transpilation: internmap, delaunator, and robust-predicates):
// jest.config.js
module.exports = {
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!d3|internmap|delaunator|robust-predicates)'
],
}
Note: The transpilation adds considerable time to the test run.
demo 3
Following the tip from Tiep Phan's answer I added the following to my package.json file:
"jest": {
"transformIgnorePatterns": ["/node_modules/(?!d3|d3-array|internmap|delaunator|robust-predicates)"] },

Next.js: Jest encountered an unexpected token. Jest failed to parse a file. Crashing due to dot ( .{color: red} ) before a className in CSS files [duplicate]

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else tooβ€”for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"jest":{
"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|scss|sass)$": "identity-obj-proxy"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
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.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

How to change babel presets for tests

I'm trying to run a very simple test with jest and vue-test-utils but I have an error while running my test.
It's a babel preset error :
And here is my babel.config.json :
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset'
]
}
Do someone have any idea what to change in my preset ?
PS : I'm working on a vue-cli project with typescript.

vuejs use babel plugin-proposal-class-properties

I have a class where I use some static properties like this:
class Entity {
static LIMIT = 10;
}
So, i can do:
Entity.LIMIT
In order to do that I'm using babel plugin-proposal-class-properties and in my .babelrc I have:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
}
I'm using jest and my test passes using that config. Now I need to use funcionality of Entity class inside a vuejs component. But I got the error:
Module parse failed: Unexpected token. You may need an appropriate loader to handle this file type
I also tried a babel config file in my project root: babel.config.js
module.exports = {
presets: ["#babel/preset-env"],
plugins: [
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
};
But didn't work.
How can i configure vuejs, to make work this babel plugin?
I'm using vue2.6.11 and vue-cli 3
I got this exact same issue when trying to use "importabular" with vuejs (vuejs 2, vue-cli-3). Importabular uses class properties, after some research I found this babel plugins (plugin-proposal-class-properties), I installed it and added it in vue.config.js.
To finally make it work, I had to add "importabular" (or the nested path) in the transpileDependencies: option. Why that? Because, by default, Babel ignores whatever is in node_module, so you have to tell Babel to not ignore this specific folder.
So, if you want to use babel or some babel plugins with some node_module with vue you should modify the vue.config.js as follow :
module.exports = {
transpileDependencies: [
'path/in/node_module',
],
}
and change the babel.config.js as follow:
module.exports = {
"presets": [
"#vue/cli-plugin-babel/preset"
],
"plugins": [
["#babel/plugin-proposal-class-properties"],
]
}