Cannot get ava transpile to work with relatively-imported files - node.js

The ES6 import works in this file, but generates an unexpected token import error when I'm importing relative files such as my Mongoose User model.
import mongoose from 'mongoose';
^^^^^^
SyntaxError: Unexpected token import
.babelrc
{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [
"transform-object-rest-spread",
"transform-async-to-generator",
"transform-export-extensions"
]
}
package.json
"ava": {
"require": [
"babel-register"
]
}
users.test.js
import test from 'ava'
import axios from 'axios'
import User from '../../models/user'
import { USER_REGISTRATION_ROUTES } from '../helpers/_test.properties.js'
test('user registration api works', async function (t) {
const email = `test${Date.now()}#example.com`
const userRegistrationData = {
email,
first_name: "john",
last_name: "doe",
password: "password"
}
await axios.post(USER_REGISTRATION_ROUTES, userRegistrationData)
.then(response => {
const data = response.data.data
const user = data.user
t.deepEqual(response.status, 200, 'Verify: response is successful')
t.deepEqual(data.registered, true, 'Verify: user is registered')
t.truthy(Object.keys(user).length > 0,
'Verify: if registered, user object is returned')
t.truthy(user.authentication_token,
'Verify: token is generated on successful registration')
})
.catch((err) => {
t.fail(`Cannot make requst to register user ${err}`)
})
User.remove({ email }, function (err) {
if (err) {
console.log('error')
} else {
console.log('success deleting test user')
}
})
})

Don't think import is supported in nodejs yet. You have to use require.
const mongoose = require('mongoose');

The answer that worked for me was the following suggested by Serge Seletskyy here. The es2017 preset is required for ES2017 features such as async await.
.babelrc
{
"presets": [
"es2017",
"#ava/stage-4",
"stage-3"
],
"plugins": [
"transform-runtime"
]
}
package.json
"ava": {
"require": [
"babel-register"
],
"babel": "inherit"
}
install modules
yarn add babel-register babel-preset-es2017 #ava/babel-preset-stage-4 babel-plugin-transform-runtime babel-preset-stage-3 --dev
Running ./node_modules/.bin/ava --verbose should now work

Non-test files are loaded through babel-register, which applies your .babelrc. However you've disabled module transpilation. I see in another comment that you're using Webpack. Try adding a environment config for Babel which restores module transpilation. From the top of my head:
{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [
"transform-object-rest-spread",
"transform-async-to-generator",
"transform-export-extensions"
],
"env": {
"test": {
"presets": [
["es2015", { "modules": true }]
]
}
}
}
This should work with the latest AVA version.

My version of Ava is 1.0.0-beta.4, and below is the solution that worked for me:
Add the following to your package.json
"ava": {
"require": [
"#babel/register"
]
}
Then npm install --save-dev #babel/register, and run test again.

Related

Eslint configuration for separated Vue component

Here is my eslintrc.json
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:vue/vue3-essential"
],
"parserOptions": {
"ecmaVersion": "latest"
},
"plugins": [
"vue",
"eslint-plugin-vue"
],
"rules": {
"vue/no-async-in-computed-properties": "error",
"vue/no-unused-vars": "error"
}
}
And This is my vue component(mycomponent.js).
I am using vue CDN to define the vue component.
const myComponent = Vue.defineComponent({
template: '#myTemplate',
components: {
'other-component': otherComponent,
},
props: {...}
watch: {...}
data() {return {...}}
methods: {
fn1() {
let a;
}
}
});
As you can see, The vue component has an unused variable in the fn1 function.
But it doesn't give any error.
Please review if there is any issues in the eslint configuration.
I already installed the eslint-plugin-vue package.

Jest: SyntaxError: Unexpected token 'export' happens at tslib.es6.js

I get this error:
C:\Users\myname\Projects\ConfigEditor\MesConfiguration.WebClient\node_modules\tslib\tslib.es6.js:24
export function __extends(d, b) {
^^^^^^
SyntaxError: Unexpected token 'export'
My jest-esm.config.mjs looks like this
const jestConfig = {
preset: 'jest-preset-angular/presets/defaults-esm',
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
useESM: true,
stringifyContentPathRegex: '\\.(html|svg)$',
tsconfig: '<rootDir>/tsconfig-esm.spec.json',
},
},
testEnvironment: 'jsdom',
moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs'],
resolver: 'jest-preset-angular/build/resolvers/ng-jest-resolver.js',
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
transform: {
'^.+\\.(ts|js|mjs|html|svg)$': 'jest-preset-angular',
},
globalSetup: 'jest-preset-angular/global-setup',
moduleNameMapper: {
//tslib: 'tslib/tslib.mjs',
tslib: 'tslib/tslib.es6.js',
"#shared/(.*)": "<rootDir>/src/app/shared/$1",
"#editors/(.*)": "<rootDir>/src/app/editors/$1",
"#dashboard/(.*)": "<rootDir>/src/app/dashboard/$1",
"#env": "<rootDir>/src/environments/environment",
},
setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
}
export default jestConfig;
package.json has
"type": "module",
I start the test with
"test-esm": "node --experimental-vm-modules --no-warnings node_modules/jest/bin/jest.js -c=jest-esm.config.mjs --no-cache",
What ist wrong?
After renaming the tslib.es6.js to tslib.mjs the error is gone, but this is no solution. It should work after any yarn install
The error is gone because you have set
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)']
you are basically using the preset jest-preset-angular/presets/defaults-esm So most of the properties you are typing in the config are redundant
One thing is that the transformIgnorePatterns somehow does not work with multiple items in that array (in some cases) so it is better to put everything at once like in my case
transformIgnorePatterns: ['node_modules/(?!rxjs|tslib)']
here is my full jest.config.js and setup-jest.ts file I am using with Angular14 with the ESM execution node --experimental-vm-modules node_modules/jest/bin/jest.js
// jest-config.ts
module.exports = {
preset: 'jest-preset-angular/presets/defaults-esm',
testRegex: '.*spec.ts$',
transformIgnorePatterns: [
'node_modules/(?!rxjs|tslib)'
],
moduleNameMapper: {
"^dnd-core$": "dnd-core/dist",
"^react-dnd$": "react-dnd/dist",
"^react-dnd-html5-backend$": "react-dnd-html5-backend/dist",
"^react-dnd-touch-backend$": "react-dnd-touch-backend/dist",
"^react-dnd-test-backend$": "react-dnd-test-backend/dist",
"^react-dnd-test-utils$": "react-dnd-test-utils/dist"
},
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};
// setup-jest.ts
import 'jest-preset-angular/setup-jest.mjs';
Object.defineProperty(window, "getComputedStyle", {
value: () => ["-webkit-appearance"]
});

How to fix that eslint complain about typescript's path aliasing

I try to import interfaces like this
import placeholder from '#/assets/images/placeholder-image.svg'
import { Button } from '#/components/atoms/buttons/Button'
but they get es-lint complain Like this.
and
Missing file extension for "#/components/atoms/buttons/Button"eslintimport/extensions
Unable to resolve path to module '#/components/atoms/buttons/Button'.eslintimport/no-unresolved
My .babelrc file is
"presets": ["#babel/react", "#babel/preset-typescript"],
"plugins": [
"#babel/plugin-transform-typescript",
"babel-plugin-typescript-to-proptypes",
"#babel/plugin-proposal-export-default-from",
["#babel/plugin-proposal-class-properties", { "loose": true }],
"#babel/plugin-proposal-object-rest-spread",
["#babel/plugin-proposal-private-methods", { "loose": true }],
["#babel/plugin-proposal-private-property-in-object", { "loose": true }],
[
"module-resolver",
{
// https://stackoverflow.com/a/57288642/2298548
"root": ["."],
"alias": {
"#/svg": "./src/svg",
"#/utils": "./src/utils",
"#/hooks": "./src/hooks",
"#/doc": "./src/doc",
"#/config": "./config",
"#/styles": "./src/styles",
"#/fonts": "./src/assets/fonts",
"#/components": "./src/components",
"#/SVGIcons": "./src/SVGIcons",
"#/base": "./src",
"#/assets": "./src/assets"
}
}
]
]
}
and my .eslintrc.js is
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
},
},
},
Does anyone have an idea for this why happen?
In path alias how we have to find a solution for linter error without disable es-lint.
Try declaring a type and then import it, check this link.
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
If the above commented solution doesn't work you might need to disable it temporary:
rules: {
'import/no-unresolved': [
'error',
{
'ignore': [ '\.svg' ]
}
]
}

node-loader not handling node_modules file

When running
npm run electron:serve
I get this error:
in ./node_modules/msnodesqlv8/build/Release/sqlserverv8.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
I think I understand the error. My webpack doesn't know how to handle the .node file in this dependency ("msnodesqlv8": "^2.2.0")
I have tried adding node-loader but I've not had any success with it. I have tried configuring it in my vue.config.js like this:
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('node')
.test(/\.node$/)
.use('node-loader')
.loader('node-loader')
.end();
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}
I also tried adding a separate webpack.config.js with no success:
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
How can I get this working?
You need to move the node loader into the chainWebpack of the electron builder for this to work.
module.exports = {
transpileDependencies: [
'vuetify'
],
configureWebpack: {
devtool: 'source-map'
},
pluginOptions: {
electronBuilder: {
preload: 'preload/preload.js',
"directories": {
"buildResources": "build"
},
// THESE NEXT 3 LINES HERE:
chainWebpackMainProcess: config => {
config.module.rule('node').test(/\.node$/).use('node-loader').loader('node-loader').end()
},
mainProcessWatch:['src/services/background/**'],
"files": [
"build/**/*",
"!node_modules"
],
"win": {
"asar": false,
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"installerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico",
"deleteAppDataOnUninstall": true
}
}
},
chainWebpack: config => {
config
.plugin('html')
.tap(args => {
args[0].title = "Configuration Utility";
return args;
});
config.module
.rule('pug')
.test(/\.pug$/)
.use('pug-plain-loader')
.loader('pug-plain-loader')
.end();
}
}

Jest didn't parse to import a file

I am trying to test my Next.js project with Jest and Enzyme. When I try to import a file from my components to test it, throws error though. Here's my files...
In the package.json my jest configuration are:
"jest": {
"setupFilesAfterEnv": "<rootDir>/jest.setup.js",
"testPathIgnorePatterns": [
"<rootDir>/.next/",
"<rootDir>/node_modules/"
],
"transform": {
"\\.(gql|graphql)$": "jest-transform-graphql",
".*": "babel-jest",
"^.+\\.js?$": "babel-jest"
}
},
"//": "I prefer this over a .babelrc file",
"babel": {
"env": {
"development": {
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
},
"production": {
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
},
"test": {
"presets": [
[
"next/babel",
{
"preset-env": {
"modules": "commonjs"
}
}
]
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
}
}
}
And subsequently in jest.setup.js :
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
However I always encounter this error anytime I want to **import a file **(In here for example I try to import a file namely "import ItemComponent from '../components/Item';"):
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". SyntaxError: Unexpected
identifier
Details:
SyntaxError: C:\Users\Welcome\Desktop\Advanced-React-master\sick-fits\frontend\__tests__\Item.test.js: Unexpected token (20:28)
18 | describe('<Item/>', () => {
19 | it('renders and matches the snapshot', () => {
> 20 | const wrapper = shallow(<ItemComponent item={fakeItem} />);
| ^
21 | expect(wrapper).toMatchSnapshot();
22 | });
23 | // it('renders and displays properly', () => {
at Parser.raise (node_modules/#babel/parser/lib/index.js:3939:15)
at Parser.unexpected (node_modules/#babel/parser/lib/index.js:5248:16)
at Parser.parseExprAtom (node_modules/#babel/parser/lib/index.js:6328:20)
at Parser.parseExprSubscripts (node_modules/#babel/parser/lib/index.js:5924:21)
at Parser.parseMaybeUnary (node_modules/#babel/parser/lib/index.js:5903:21)
at Parser.parseExprOps (node_modules/#babel/parser/lib/index.js:5812:21)
at Parser.parseMaybeConditional (node_modules/#babel/parser/lib/index.js:5784:21)
at Parser.parseMaybeAssign (node_modules/#babel/parser/lib/index.js:5731:21)
at Parser.parseExprListItem (node_modules/#babel/parser/lib/index.js:6995:18)
at Parser.parseCallExpressionArguments (node_modules/#babel/parser/lib/index.js:6124:22)
Any help would be appreciated
Try removing these two lines from your package.json:
".*": "babel-jest",
"^.+\\.js?$": "babel-jest"
In theory, these shouldn't be needed: https://jestjs.io/docs/en/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
The custom configuration you have added might be causing issues. In theory, jest should transform your js files by default using babel-jest. I've certainly had a recent NextJS project work with jest with no babel-jest config declared in my package.json.

Resources