in my previous project i used this syntax for migration to mongoDB:
my_migration.js //
'use strict';
import slug from 'slugify';
module.exports = {
async up(db) {
const categories = [
{
title: 'football',
slug: slug('football'),
createdAt: new Date().getTime(),
updatedAt: new Date().getTime()
},
];
await db.collection('categories').insertMany(categories);
}
};
And it works, but an another project(Nextjs, Reactjs, Nodejs) I have eslint error:
[eslint] Parsing error: Unexpected token up
(method) up(db: any): Promise<void>
What I am doing incorrect? Thanks for any help.
eslintrc.js/
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"ecmaVersion": 2017,
"sourceType": "module"
},
Related
I am using in my next js application Cypress and Jest. Running jest --coverage i get an error:
STACK: 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'],
]
This is my .babelrc file:
{
"presets": ["next/babel"],
"plugins": ["istanbul"]
}
Who faced with the same issue and how to solve it to get the coverage?
I found the solution that helped to solve the problem.
I had to add the env variable to the .babelrc
{
"env": {
"component": {
"plugins": [
"istanbul"
]
}
}
}
Then add it to cypress.config.js
const { defineConfig } = require('cypress');
const { devServer } = require('#cypress/webpack-dev-server');
const webpackConfig = require('./config/cypress.webpack.config.js');
const codeCoverageTask = require('#cypress/code-coverage/task');
module.exports = defineConfig({
viewportWidth: 1000,
viewportHeight: 660,
video: false,
env: {
BABEL_ENV: 'component',
},
component: {
devServer(devServerConfig) {
return devServer({
...devServerConfig,
framework: 'react',
webpackConfig,
});
},
specPattern: 'src/**/*.cy.{js,ts,jsx,tsx}',
setupNodeEvents(on, config) {
codeCoverageTask(on, config);
return config;
},
},
});
Basically, every time that i create a TYPESCRIPT gatsby project, i get errors on the file gatsby-config.ts.
Errors are in bold font.
import type { GatsbyConfig } from "gatsby";
require('dotenv').config({
path: `.env.${process.env.NODE_ENV}`,
});
const strapiConfig = {
apiURL: process.env.STRAPI_API_URL,
accessToken: process.env.STRAPI_TOKEN,
collectionTypes: ['article', 'company', 'author'],
singleTypes: [],
};
const config: GatsbyConfig = {
siteMetadata: {
title: ``,
siteUrl: `https://www.yourdomain.tld`
},
plugins: ["gatsby-plugin-sass", {
resolve: 'gatsby-plugin-google-analytics',
options: {
"trackingId": "portfolio-vanny-1"
}
}, "gatsby-plugin-image", "gatsby-plugin-react-helmet", "gatsby-plugin-mdx", "gatsby-transformer-remark", "gatsby-plugin-sharp", "gatsby-transformer-sharp", {
resolve: 'gatsby-source-filesystem',
options: {
"name": "images",
"path": "./src/images/"
},
***__key: "images"***
}, {
resolve: 'gatsby-source-filesystem',
options: {
"name": "pages",
"path": "./src/pages/"
},
**__key: "pages"**
},
{
resolve: `gatsby-source-strapi`,
options: strapiConfig,
}]
};
export default config;
It seems that those errors doesnt affect anything on my project but its weird, i dont even touch the code and it throws me those errors.
I'm working on a nextjs 10.1.3 built-in web application. We implemented a web worker to boost up the performance in one of the pages and the plan is to continue adding more workers; also, all the code is properly unit tested, and using the worker-loader in previous webpack versions (4th and below) we were able to test it.
With the new webpack 5 version, the worker-loader plugin is not needed anymore; instead, the way to load a web worker using the new version is new Worker(new URL("#/workers/task.worker.js", import.meta.url));.
Doing it this way, my code is working as expected with npm build && npm start; however, when I try to add the respective unit tests I got the following error: Cannot use 'import.meta' outside a module and everything happens because of the import.meta.url used to add the location of the worker in the browser.
I read many posts on the web regarding babel but I want to get away from that option. Is there any other option to mock the import.meta.url with jest?
Any help will be very welcome. This is the current configuration.
package.json
{
...
"#babel/core": "^7.8.6",
"next": "^10.1.3",
"react": "^16.13.0",
"webpack": "^5.37.1"
"devDependencies": {
...
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"jest": "^24.9.0",
"jest-cli": "^25.1.0",
...
}
...
}
next.config.js
const {
...
} = process.env;
const basePath = "";
const COMMIT_SHA = [];
const { parsed: localEnv } = require("dotenv").config();
const webpack = require("webpack");
const withBundleAnalyzer = require("#next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
const nextConfig = {
env: {
NEXT_PUBLIC_COMMIT_SHA: COMMIT_SHA,
},
images: {
domains: [
"...",
],
},
future: {
webpack5: true,
},
productionBrowserSourceMaps: true,
trailingSlash: true,
reactStrictMode: true,
webpack: (config, options) => {
if (localEnv) {
config.plugins.push(new webpack.EnvironmentPlugin(localEnv));
} else {
config.plugins.push(new webpack.EnvironmentPlugin(process.env));
}
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: "url-loader",
options: {
limit: 100000,
name: "[name].[ext]",
},
},
});
config.output = {
...config.output,
chunkFilename: options.isServer
? `${options.dev ? "[name]" : "[name].[fullhash]"}.js`
: `static/chunks/${options.dev ? "[name]" : "[name].[fullhash]"}.js`,
publicPath: `/_next/`,
globalObject: `(typeof self !== 'undefined' ? self : this)`,
};
config.plugins.push(new webpack.IgnorePlugin(/pages.*\/__tests__.*/));
config.plugins.push(
new options.webpack.DefinePlugin({
"process.env.NEXT_IS_SERVER": JSON.stringify(
options.isServer.toString()
),
})
);
return config;
},
};
module.exports = withBundleAnalyzer(nextConfig);
The useEffect worker
useEffect(() => {
if (pageData.data?.length) {
workerRef.current = new Worker(new URL("#/workers/task.worker.js", import.meta.url));
workerRef.current.addEventListener("message", result => {
if (result.error) {
setWorkerError();
} else {
updateData(result.data);
}
});
const ids = pageData.data.map(store => store.id);
workerRef.current.postMessage(ids);
} else {
setNoDataFound();
}
return () => {
workerRef.current && workerRef.current.terminate();
};
}, []);
jest.config.js
module.exports = {
moduleDirectories: ["node_modules", "src", "static", "store"],
modulePathIgnorePatterns: [
"<rootDir>/node_modules/prismjs/plugins/line-numbers",
],
testPathIgnorePatterns: [
"<rootDir>/src/components/component-library",
"<rootDir>/.next",
"jest.config.js",
"next.config.js",
],
collectCoverageFrom: [
"**/src/**",
"**/store/**",
"**/pages/**",
"!**/__tests__/**",
"!**/node_modules/**",
"!**/component-library/**",
],
testEnvironment: "node",
collectCoverage: true,
verbose: false,
automock: false,
setupFiles: ["./setupTests.js"],
moduleNameMapper: {
"#/components/(.*)$": "<rootDir>/src/components/$1",
"#/functions/(.*)$": "<rootDir>/src/components/functions/$1",
"#/services/(.*)$": "<rootDir>/src/components/services/$1",
"#/workers/(.*)$": "<rootDir>/src/components/workers/$1",
"#/scripts(.*)$": "<rootDir>/src/scripts/$1",
"#/src(.*)$": "<rootDir>/src/$1",
"#/__mocks__(.*)$": "<rootDir>/__mocks__/$1",
"#/pages(.*)$": "<rootDir>/pages/$1",
"#/store(.*)$": "<rootDir>/store/$1",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
},
coveragePathIgnorePatterns: ["/node_modules/"],
coverageThreshold: {
global: {
branches: 67,
functions: 66,
lines: 73,
statements: 72,
},
},
runner: "groups",
extraGlobals: [],
testTimeout: 10000,
};
In my setup (typescript + ts-jest) I prepended the following node option to make it work:
NODE_OPTIONS=--experimental-vm-modules
Reference can be found here: https://jestjs.io/docs/ecmascript-modules
I am trying to define a function as you see below.
const fetchRoles = async () => {
const fetchedRoles = await axiosInstance.get('/roles/');
setRoles(fetchedRoles.data)
}
And I am getting error "Unexpected token () ^=>".
Why I am getting this error ?
I am using node version v12.18.2 and npm version 6.14.7
Thanks..
I solved the problem.
For their person who may experience this problem,
This error comes from eslint-loader. So I updated eslint config with ecmaVersio 8 and problem solved.
My parser conf,
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module",
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
}
}
I am testing React, Redux App with Jest.
Jest test works well with a simple function test.
but an action creator test is failing throwing the error message below. It is working creator code. Dispatching this action creator in a component updates the state.
TypeError: (0 , _reserve.saveReserveInfo) is not a function
5 | const id = 'date';
6 | const value = '2018-09-30';
> 7 | const action = saveReserveInfo(id, value);
| ^
8 | expect(action).toEqual({
9 | type: types.SAVE_RESERVE_INFO,
10 | id: 'date',
actionTypes.js
module.exports = {
SAVE_RESERVE_INFO: 'SAVE_RESERVE_INFO',
OPEN_RESERVE: 'OPEN_RESERVE',
};
reserve.action.js
import * as types from '../actionTypes';
export const saveReserveInfo = (id, value) => {
return {
type: types.SAVE_RESERVE_INFO,
id,
value,
};
};
export const openReserve = () => ({
type: types.OPEN_RESERVE,
});
reserve.test.js
import * as types from '../../components/actionTypes';
import { saveReserveInfo } from '../../components/reserve/reserve.action';
test('should create an action to update reserve info', () => {
const id = 'date';
const value = '2018-09-30';
const action = saveReserveInfo(id, value);
expect(action).toEqual({
type: types.SAVE_RESERVE_INFO,
id: 'date',
value: '2018-09-30',
});
});
client/jest.config.js
module.exports = {
displayName: 'client',
setupTestFrameworkScriptFile: require.resolve(
'../test/setup-test-framework.js',
),
modulePaths: ['<rootDir>/src'],
moduleNameMapper: {
'\\.scss||css$': require.resolve('../test/style-mock.js'),
'\\.svg$': require.resolve('../test/svg-file-mock.js')
},
};
jest.config.js
module.exports = {
testMatch: ['**/__test__/**'],
testPathIgnorePatterns: ['/node_modules/'],
coverageDirectory: './coverage',
collectCoverageFrom: [
'**/src/**/*.js',
'!**/__test__/**',
'!**/node_modules/**',
],
coverageThreshold: {
global: {
statements: 18,
branches: 10,
functions: 19,
lines: 18,
},
},
projects: ['./client', './server'],
};
babelrc.js
const isTest = String(process.env.NODE_ENV) === 'test';
module.exports = {
presets: [
[
'env',
{
targets: {
browsers: ['last 2 versions', 'safari >= 7'],
node: 'current',
},
loose: true,
modules: isTest ? 'commonjs' : false,
debug: isTest ? false : true,
},
],
'react',
],
retainLines: true,
plugins: [
[
'transform-runtime',
{
helpers: false,
polyfill: false,
regenerator: true,
moduleName: 'babel-runtime',
},
],
'transform-class-properties',
'transform-object-rest-spread',
'syntax-dynamic-import',
isTest ? 'dynamic-import-node' : null,
].filter(Boolean),
env: {
development: {
plugins: ['react-hot-loader/babel'],
},
},
};
version
jest: 23.5.0,
jest-dom: 1.12.0,
react: 16.4.2,
react-dom: 16.4.2,
react-redux: 5.0.7,
redux: 4.0.0,
Here is the project zip file.
Thank you !!
To answer my question,
here is my working jest config file.
jest.config.js
module.exports = {
testMatch: ['**/__test__/**'],
testPathIgnorePatterns: ['/node_modules/'],
coverageDirectory: './coverage',
collectCoverageFrom: [
'**/src/**/*.js',
'!**/__test__/**',
'!**/node_modules/**',
],
projects: ['./client', './server'],
};
I deleted coverageThreshold.
Testing was failing as there was less than specified threshold.
Jest coverageThreshold