Proper Jest configuration with React-native 0.56 - react-native

After upgrading to react-native 0.56 I'm experiencing tons of babel reated errors on jest specs that used to run just fine.
I realize that react-native 0.56 requires babel7 and that's probably related but I don't have enough experience/understaanding in babel to figure out what I'm missing.
Some error examples:
/xxx/spec/Bootstrap.test.js:6
import thunk from 'redux-thunk';
^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
another:
import { rootReducer } from '../store';
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
My package.json jest config is as follows:
"jest": {
"preset": "react-native",
"collectCoverage": true,
"coverageReporters": [
"cobertura",
"lcov"
],
"coverageDirectory": "coverage",
"globals": {
"__TEST__": true
},
"moduleNameMapper": {
"styled-components": "<rootDir>/node_modules/styled-components/dist/styled-components.native.cjs.js"
},
"moduleDirectories": [
"node_modules",
"/"
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|react-navigation)/"
],
"setupFiles": [
"jest-localstorage-mock",
"./node_modules/appcenter/test/AppCenterMock.js",
"./node_modules/appcenter-analytics/test/AppCenterAnalyticsMock.js",
"./node_modules/appcenter-crashes/test/AppCenterCrashesMock.js"
]
},
.babelrc is defined as follows:
{
"presets": ["react-native"],
"env": {
"development": {
"plugins": ["transform-class-properties"]
},
"test": {
"plugins": ["transform-class-properties"]
}
}
}
I also have the following devdependencies:
"#babel/core": "^7.0.0-beta.52",
"babel-core": "^7.0.0-beta.52",
"babel-eslint": "~8.2.5",
"babel-plugin-module-resolver": "^3.1.1",
"babel-plugin-transform-class-properties": "~6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-preset-expo": "~4.0.0",
"babel-preset-react-native": "^5.0.1",
"babel-preset-react-native-stage-0": "^1.0.1",
"babel-preset-stage-0": "^6.24.1",
I've tried several approaches but couldn't progress much.
Besides the jest environment, the application runs fine.

Details of the workaround I did to move on, while 0.57 wasn't ready:
Basically I had to create 2 config files:
jest-acceptance.config (with the following relevant snippets)
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/custom_b7_processor.js"
},
"testRegex": "(/test/.*|(\\.|/)spec)\\.js$",
jest-unit.config (with the following relevant snippets)
"preset": "react-native",
"testRegex": "(/test/.*|(\\.|/)test)\\.js$",
That custom_b7_processor, is some sort of internal code from react-native:
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* #format
* #flow
*/
/* eslint-disable */
'use strict';
const {transformSync: babelTransformSync} = require('#babel/core');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const babelRegisterOnly = require('metro-babel-register');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const generate = require('#babel/generator').default;
const nodeFiles = RegExp(
[
'/local-cli/',
'/metro(?:-[^/]*)?/', // metro, metro-core, metro-source-map, metro-etc
].join('|'),
);
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
/* $FlowFixMe(site=react_native_oss) */
const transformer = require('metro/src/reactNativeTransformer');
module.exports = {
process(src /*: string */, file /*: string */) {
if (nodeFiles.test(file)) {
// node specific transforms only
return babelTransformSync(
src,
Object.assign(
{filename: file},
{sourceType: 'script', ...nodeOptions, ast: false},
),
).code;
}
const {ast} = transformer.transform({
filename: file,
localPath: file,
options: {
ast: true, // needed for open source (?) https://github.com/facebook/react-native/commit/f8d6b97140cffe8d18b2558f94570c8d1b410d5c#r28647044
dev: true,
inlineRequires: true,
platform: '',
projectRoot: '',
retainLines: true,
sourceType: 'unambiguous', // b7 required. detects module vs script mode
},
src,
plugins: [
[require('#babel/plugin-transform-block-scoping')],
// the flow strip types plugin must go BEFORE class properties!
// there'll be a test case that fails if you don't.
[require('#babel/plugin-transform-flow-strip-types')],
[
require('#babel/plugin-proposal-class-properties'),
// use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
{loose: true},
],
[require('#babel/plugin-transform-computed-properties')],
[require('#babel/plugin-transform-destructuring')],
[require('#babel/plugin-transform-function-name')],
[require('#babel/plugin-transform-literals')],
[require('#babel/plugin-transform-parameters')],
[require('#babel/plugin-transform-shorthand-properties')],
[require('#babel/plugin-transform-react-jsx')],
[require('#babel/plugin-transform-regenerator')],
[require('#babel/plugin-transform-sticky-regex')],
[require('#babel/plugin-transform-unicode-regex')],
[
require('#babel/plugin-transform-modules-commonjs'),
{strict: false, allowTopLevelThis: true},
],
[require('#babel/plugin-transform-classes')],
[require('#babel/plugin-transform-arrow-functions')],
[require('#babel/plugin-transform-spread')],
[require('#babel/plugin-proposal-object-rest-spread')],
[
require('#babel/plugin-transform-template-literals'),
{loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
],
[require('#babel/plugin-transform-exponentiation-operator')],
[require('#babel/plugin-transform-object-assign')],
[require('#babel/plugin-transform-for-of'), {loose: true}],
[require('#babel/plugin-transform-react-display-name')],
[require('#babel/plugin-transform-react-jsx-source')],
],
});
return generate(
ast,
{
code: true,
comments: false,
compact: false,
filename: file,
retainLines: true,
sourceFileName: file,
sourceMaps: true,
},
src,
).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
require.resolve('metro/src/reactNativeTransformer'),
require.resolve('#babel/core/package.json'),
]),
};
At my .babelrc I had to include the following:
"presets": ["./node_modules/babel-preset-react-native-b6"],
That is pointing to a fork I made of the babel preset that React-native was using at 0.56-
https://github.com/lhrolim/babel-preset-react-native.
At my package.json I had te following babel dependencies
"babel-preset-react-native": "~5.0.2",
"babel-preset-react-native-b6": "github:lhrolim/babel-preset-react-native",
The test scripts I used then:
"test": "npm run test-acc && npm run test-unit",
"test-acc": "jest --config=jest_acceptance-config.json",
"test-unit": "jest --config=jest_unit-config.json",
I believe there might be some redundancies here and there, but that's what worked for me.

Related

Critical dependency: the request of a dependency is an expression, vue.js

My testing-app is compiling fine, except that I get this warning:
" Critical dependency: the request of a dependency is an expression"
(base) marco#pc01:~/webMatters/vueMatters/PeerJS-VueJS-Test$ npm run serve
> testproject#0.1.0 serve /home/marco/webMatters/vueMatters/PeerJS-VueJS-Test
> vue-cli-service serve
INFO Starting development server...
98% after emitting CopyPlugin
WARNING Compiled with 1 warnings
7:22:25 PM
warning in ./node_modules/peerjs/dist/peerjs.min.js
Critical dependency: the request of a dependency is an expression
App running at:
- Local: http://localhost:8080
- Network: http://ggc.world/
Note that the development build is not optimized.
To create a production build, run npm run build.
I read around that it might depend of webpack, but didn't find how to put it right.
This is webpack.config.js :
{
"mode": "development",
"output": {
"path": __dirname+'/static',
"filename": "[name].[chunkhash:8].js"
},
"module": {
"rules": [
{
"test": /\.vue$/,
"exclude": /node_modules/,
"use": "vue-loader"
},
{
"test": /\.pem$/,
"use": "file-loader"
}
]
},
node: {
__dirname: false,
__filename: false
},
resolve: {
extension: ['*', '.pem'],
},
devServer: {
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
https: true,
compress: true,
public: 'ggc.world:8080'
}
}
Any ideas about how to solve it?
The following code works for me. Edit vue.config.js and add webpack config:
configureWebpack: {
module: {
exprContextCritical: false
}
}
const webpack = require('webpack');
module.exports = {
// ... your webpack configuration ...
plugins: [
new webpack.ContextReplacementPlugin(
/\/package-name\//,
(data) => {
delete data.dependencies[0].critical;
return data;
},
),
]
}
try this one
For people coming here using CRA and having trouble with PeerJS, install react-app-rewired and use the following override config and it should work.
/* config-overrides.js */
const webpack = require('./node_modules/webpack')
module.exports = function override (config, env) {
if (!config.plugins) {
config.plugins = []
}
config.plugins.push(
new webpack.ContextReplacementPlugin(
/\/peerjs\//,
(data) => {
delete data.dependencies[0].critical
return data
}
)
)
return config
}
It seems it is an error between the library bundler (parcel) and CRA bundler (webpack), and I couldn't find any official fix on the way.

ES6/ES7 support with serverless

I have few serverless project created without using ES6/ES7 support. In our new project, i wanted to integrate this with serverless but not able to get it going.
Here is my serverless.yml file
#sls offline start --skipCacheInvalidation
service: test
provider:
name: aws
runtime: nodejs8.10 # set node.js runtime
memorySize: 1024 # set the maximum memory of the Lambdas in Megabytes
timeout: 300 # the timeout is 10 seconds (default is 6 seconds)
stage: ${opt:stage, 'dev'} #${self:provider.stage} # setting the env stage to dev, this will be visible in the routes
region: us-east-1
logRetentionInDays: 14 # Set the default RetentionInDays for a CloudWatch LogGroup
deploymentBucket:
name: api-test
# custom:
# stage: ${opt:stage, self:provider.stage}
environment: ${file(env.yml):${self:provider.stage}}
plugins:
- serverless-webpack
- serverless-offline
# serverless optimization
package:
individually: true
# serverless-webpack configuration
# Enable auto-packing of external modules
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
functions:
createCampaign:
handler: src/Campaign.CreateCampaign
name : campaign-createcampaign-${self:provider.stage} #custom lambda name instead of auto generated
description: To create campaign
events:
- http:
path: campaign
method: post
cors: true
getAllCampaign:
handler: src/Campaign.GetCampaign
name : campaign-getall-${self:provider.stage} #custom lambda name instead of auto generated
description: To retrieve all campaign
events:
- http:
path: campaign
method: get
cors: true
My campaign.js is under /src folder in my code. I tried this using https://medium.com/#kilgarenone/write-es6-es7-in-serverless-framework-using-babel-7-and-webpack-4-5bd742168e1a
My webpack config is following.
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
//entry: slsw.lib.entries,
entry: {handler : './src/Campaign.js'},
target: 'node',
// Generate sourcemaps for proper error messages
devtool: 'source-map',
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
optimization: {
// We no not want to minimize our code.
minimize: false,
},
performance: {
// Turn off size warnings for entry points
hints: false,
},
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: __dirname,
exclude: /node_modules/,
},
],
},
};
My package.json is
{
"name": "orim-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"babel-loader": "^8.0.5",
"babel-plugin-source-map-support": "^2.0.1",
"serverless-offline": "^4.9.4",
"serverless-webpack": "^5.3.0",
"webpack": "^4.30.0",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"dotenv": "^7.0.0",
"mongoose": "^5.5.5",
"source-map-support": "^0.5.12"
}
}
My .babelrc file is
{
"plugins": ["source-map-support", "transform-runtime"],
"presets": [
["env", { "node": "8.10" }],
"stage-3"
]
}
When i execute sls offline start --SkipCacheInvalidateion, i get following warning
WARNING in ./src/Campaign.js 5:12-29
"export 'connectToDatabase' was not found in '../db'
And it seems like webpack and babel-loader isn't transpile my entire code
From the doc, this is something you can try:
// webpack.config.js
const _ = require('lodash');
const slsw = require('serverless-webpack');
module.exports = {
...
entry: _.assign({
handler : './src/Campaign.js'
}, slsw.lib.entries),
...
};

Why babelConfig not working in webpack encore?

I want to add support for async / await functions for my project.
I install
"#babel/core": "^7.2.0",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.2.0",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-stage-2": "^7.0.0",
"#babel/runtime": "^7.2.0",
It's my webpack.config.js
const Encore = require('#symfony/webpack-encore');
Encore
.setOutputPath('public/build')
.setPublicPath('/build')
.addEntry('app', './assets/app.js')
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableVueLoader()
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})
;
const config = Encore.getWebpackConfig();
config.externals = {
mode: 'development',
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:80',
devServer: {
public: 'http://localhost:3000',
disableHostCheck: true,
},
})
};
config.node = {
fs: "empty"
};
module.exports = config;
When I run a server dev, I get an error.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
I can not understand what the problem is.
I also created a .babelrc file and wrote the same configuration in it. But unfortunately, this did not help (
Use .babelrc for change babel config like this. This file should be in your project root
{
"plugins": ["#babel/plugin-transform-runtime"],
"presets": [
[
"#babel/preset-env",
...
],
...
]
}
Then remove this from your webpack.config.js
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})

Webdriver io autocomplete in VS Code

I'm using Webdriver IO as the e2e testing framework. But this autocomplete issue is really slowing me down. VS Code doesn't auto complete the global variable browser and it's methods.
.eslintrc
{
"extends": ["eslint:recommended", "standard"],
"parser": "babel-eslint",
"plugins": [
"mocha",
"webdriverio"
],
"env": {
"webdriverio/wdio": true,
"mocha": true
},
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module"
},
"rules": {
"indent": ["error", 4]
}
}
.babelrc
{
"presets": ["es2015"],
"plugins": [
["transform-runtime", {
"polyfill": false
}]
]
}
I think you can use TypeScript typings.
Add 2 dependencies to package.json:
"#types/node": "^8.5.2",
"#types/webdriverio": "^4.8.7",
Install them, reload project. If autocomplete does not yet works, create
tsconfig.json in root of your project:
{
"compilerOptions": {
"allowJs": true,
"outDir": "./.built/"
}
}
You don't need to use typescript compiler, it will just provide autocomplete. Continue writing your js code as usual.
But if you wish to use typescript, here is small beginner guide:
http://webdriver.io/guide/getstarted/configuration.html#Setup-TypeScript

Aurelia Bundling error

I am using a modified aurelia-navigation-skeleton to build my project (modified because I am also adding a servicestack backend).
First the error:
[16:33:59] Error tracing npm:crypto-browserify#3.11.0/example/bundle.js at file:///C:/MyProjectPath/jspm_packages/npm/crypto-browserify#3.11.0/example/bundle.js
Error: Unable to calculate canonical name to bundle file:///test.js. Ensure that this module sits within the baseURL or a wildcard path config.
at getCanonicalNamePlain (C:\MyProjectPath\node_modules\systemjs-builder\lib\utils.js:227:13)
at getCanonicalName (C:\MyProjectPath\node_modules\systemjs-builder\lib\utils.js:150:19)
at C:\MyProjectPath\node_modules\systemjs-builder\lib\trace.js:565:36
at run (C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\es6.promise.js:87:22)
at C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\es6.promise.js:100:28
at flush (C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\_microtask.js:18:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I am not using crpto-browserify myself so I assume it is a dependency somewhere either within the skeleton or within Aurelia itself.
Project layout:
ProjectRoot
-- build (from skeleton)
-- tasks
-- src (standard aurelia layout here)
-- app.js/main.js/app.html
-- views
-- resources
-- etc...
-- default.html
-- node_modules
-- jspm_packages
-- jspm.config.js
-- package.json
jspm.config.js
System.config({
defaultJSExtensions: true,
transpiler: "typescript",
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"aurelia-animator-css": "npm:aurelia-animator-css#1.0.1",
"aurelia-api": "npm:aurelia-api#3.1.1",
"aurelia-authentication": "npm:aurelia-authentication#3.3.0",
"aurelia-bootstrapper": "npm:aurelia-bootstrapper#2.1.1",
"aurelia-dependency-injection": "npm:aurelia-dependency-injection#1.3.0",
"aurelia-dialog": "npm:aurelia-dialog#1.0.0-beta.3.0.1",
"aurelia-fetch-client": "npm:aurelia-fetch-client#1.1.1",
"aurelia-framework": "npm:aurelia-framework#1.1.0",
"aurelia-pal-browser": "npm:aurelia-pal-browser#1.1.0",
"aurelia-router": "npm:aurelia-router#1.2.1",
"aurelia-templating-binding": "npm:aurelia-templating-binding#1.3.0",
"bootstrap": "github:twbs/bootstrap#3.3.7",
"font-awesome": "npm:font-awesome#4.7.0",
"moment": "npm:moment#2.17.1",
"numeral": "npm:numeral#2.0.4",
"servicestack-client": "npm:servicestack-client#0.0.26",
"text": "github:systemjs/plugin-text#0.0.9",
"typescript": "npm:typescript#2.2.1",
"github:jspm/nodelibs-assert#0.1.0": {
"assert": "npm:assert#1.4.1"
},
...
...
...
}
bundle.js
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var bundles = require('../bundles.js');
var config = {
force: true,
baseURL: '.',
configPath: './jspm.config.js',
bundles: bundles.bundles
};
gulp.task('bundle', ['build'], function() {
return bundler.bundle(config);
});
gulp.task('unbundle', function() {
return bundler.unbundle(config);
});
bundles.js
module.exports = {
"force": true,
"packagePath": ".",
"configPath": [ // SystemJS/JSPM configuration files
"./jspm.config.js"
],
"injectionConfigPath": "./jspm.config.js",
"bundles": {
"dist/app-build": {
"includes": [
"[**/*.js]",
"**/*.html!text",
"**/*.css!text"
],
"options": {
"inject": true,
"minify": true,
"depCache": false,
"rev": true
}
},
"dist/aurelia": {
"includes": [
"aurelia-api",
"aurelia-authentication",
"aurelia-framework",
"aurelia-pal-browser",
"aurelia-bootstrapper",
"aurelia-dependency-injection",
"aurelia-dialog",
"aurelia-fetch-client",
"aurelia-router",
"aurelia-animator-css",
"aurelia-templating-binding",
"aurelia-polyfills",
"aurelia-templating-binding",
"aurelia-templating-resources",
"aurelia-templating-router",
"aurelia-loader-default",
"aurelia-history-browser",
"aurelia-logging-console",
"moment",
"numeral",
"servicestack-client",
"bootstrap",
"bootstrap/css/bootstrap.css!text"
],
"options": {
"inject": true,
"minify": true,
"depCache": false,
"rev": true
}
}
}
};
The error means nothing to me and other posts about this error talk about changing the BaseURL, but I don't know what I would change it to to make this work. Any help would be appreciated.