I'm configuring simple project for testing using jest and babel. How do i make them work together ?
I have tried instructions mentioned here: https://jestjs.io/docs/en/getting-started but couldn't accomplish it.
abc.test.js
import {PI} from "./mathconsts";
describe("tests",()=>{
test('assert pi', () => {
expect(PI).toBe(3.14);
});
});
mathconsts.js
export const PI = 3.14;
package.json
{
"name": "simple-testing",
"version": "1.0.0",
"description": "Project to write simple tests",
"main": "index.js",
"scripts": {
"test": "jest"
},
"dependencies": {
"axios": "0.19.0",
"dotenv": "8.1.0"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-jest": "^24.9.0",
"jest": "24.9.0",
"prettier": "1.18.2"
}
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
jest.config.js
module.exports = {
transformIgnorePatterns: [
"/node_modules/"
],
}
error found:
● 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/tests/abc.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { PI } from "./mathconsts";
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
How do i make it run ?
Related
I want to test a component for my vue nuxt3 project and i got error when i test with js. The problem is,
> test
> jest
FAIL __tests__/test.js
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
C:\Users\Emirhan\Desktop\Emir\amazon-backend\__tests__\test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { mount } from '#vue/test-utils';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1598:14)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.104 s
Ran all test suites.
when i , npm run test. it does not work.
Here is jest.config.js
module.exports = {
preset: '#vue/cli-plugin-unit-jest',
testEnvironment: 'jsdom'
}
Here my test.js,
import {mount} from '#vue/test-utils';
import MainSignUp from '#/components/MainSignUp.vue';
describe('SignUp component unit test: ', () => {
test('renders task 111', () => {
const wrapper = mount(MainSignUp, {
propsData: {
user: {name:"user 123",
completed:false
}
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
test('renders task 222', () => {
const wrapper = mount(MainSignUp, {
propsData: {
user: {name:"user 321321312",
completed:false
}
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
And here is my package.json file,
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"test": "jest",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"#vue/vue3-jest": "28",
"jest": "^29.4.1",
"jest-environment-jsdom": "^29.4.1",
"nuxt": "^3.1.0",
"vue3-jest": "^27.0.0-alpha.1"
},
"dependencies": {
"#nozomuikuta/h3-cors": "^0.2.0",
"#nuxtjs/vuetify": "^1.12.3",
"#pinia/nuxt": "^0.4.6",
"#vue/cli-plugin-unit-jest": "^5.0.8",
"#vue/test-utils": "^2.2.8",
"axios": "^1.2.6",
"body-parser": "^1.20.1",
"express": "^4.18.2",
"firebase": "^9.16.0",
"nuxt-vuefire": "^0.1.5",
"pinia": "^2.0.29",
"sass": "^1.57.1",
"vuefire": "^3.0.1",
"vuetify": "^3.1.2"
},
"overrides": {
"vue": "latest"
}
}
I can not solve this issue. What can i do ?
Why do I keep getting error message "SyntaxError: Cannot use import statement outside a module" when I use Babel and Jest?
I have a super simple app that contains two modules:
// moduleTwo.mjs:
let testFuncOneModTwo = () => {
return ('String generated by fn in moduleTwo.mjs')
}
export {testFuncOneModTwo }
/////////////
// moduleOne.mjs:
import {testFuncOneModTwo} from './moduleTwo.mjs'
let testFuncOneModOne = () => {
return (testFuncOneModTwo())
}
export { testFuncOneModOne }
//////////////
Here's my Jest test file:
// myTest.test.js:
import * as myImports from './moduleOne.mjs';
test('tests fn in module that calls fn in another module.', () => {
expect(myImports.testFuncOneModOne()).toEqual( 'String generated by fn in
moduleTwo.mjs' );
});
/////////////
// babel.config.json:
{
"presets": ["#babel/preset-env"]
}
// package.json:
{
"name": "JestIsVeryTesting",
"version": "1.0.0",
"description": "",
"main": "moduleOne.mjs",
"scripts": {
"test": "jest --coverage "
},
"jest": {
"transform": {
"^.+\\.js?$": "babel-jest"
}
},
"dependencies": {
"#babel/runtime": "^7.18.6"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.18.6",
"#babel/preset-env": "^7.18.6",
"babel": "^6.23.0",
"babel-jest": "^28.1.2",
"jest": "^28.1.2"
}
}
// The error message (edited by me):
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. ...
...
...
Details:
/xxx/xxx/xxx/xxx/moduleOne.mjs:91
import { testFuncOneModTwo } from './moduleTwo.mjs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
> 2 | import * as myImports from './moduleOne.mjs';
| ^
3 |
4 | test('tests fn in module that calls fn in another module.', () => {
5 | expect(myImports.testFuncOneModOne()).toEqual( 'This string returned by a function in moduleTwo.mjs' );
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (myTest.test.js:2:1)
Help would be much appreciated as this is driving me mad.
In case anyone is interested I solved the problem myself in the end:
To the top level of the package.json file I added:
"type": "module"
This tells node that all files in the project that end with '.js' are ES6 files
I changed the extensions of my modules to '.js'
(so that
'moduleOne.mjs' became 'moduleOne.js'
and
'moduleTwo.mjs' became 'moduleTwo.js'
)
This is in keeping with the value of the package.json file's "jest" field, which has value:
"transform": {
"^.+\\.js?$": "babel-jest"
}
I'm building a Nuxt-electron-prisma app and I kinda stuck here. when I use prisma normally as guided every thing is fine on dev but on build i get this error :
A javascript error occurred in the main process
Uncaught exception:
Error: can not find module : '.prisma/client'
I tried changing prisma provider output to ../resources/prisma/client
generator client {
provider = "prisma-client-js"
output = "../resources/prisma/client"
}
and in main.js of electron
const { PrismaClient } = require('../resources/prisma/client');
const prisma = new PrismaClient()
but I get error Cannot find module '_http_common' at webpackMissingModules in both dev and build ! which by others opinion is caused when using prisma on client-side but I only use it on background.js (main.js of the my boilerplate)
I'm using Nuxtron boilerplate for Nuxt-electron which is using yml file for electron-builder config file and in it I also added prisma to files property:
appId: com.example.app
productName: nuxt-electron-prisma
copyright: Copyright © 2021
nsis:
oneClick: false
perMachine: true
allowToChangeInstallationDirectory: true
directories:
output: dist
buildResources: resources
files:
- "resources/prisma/database.db"
- "node_modules/.prisma/**"
- "node_modules/#prisma/client/**"
- from: .
filter:
- package.json
- app
publish: null
and still get errors
in my win-unpacked/resources I have this only: win-unpacked\resources\app.asar.unpacked\node_modules\#prisma\engines
and of course my package.json
{
"private": true,
"name": "nuxt-electron-prisma",
"productName": "nuxt-electron-prisma",
"description": "",
"version": "1.0.0",
"author": "",
"main": "app/background.js",
"scripts": {
"dev": "nuxtron",
"build": "nuxtron build"
},
"dependencies": {
"electron-serve": "^1.0.0",
"electron-store": "^6.0.1",
"#prisma/client": "^3.0.2"
},
"devDependencies": {
"#mdi/font": "^6.1.95",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/device": "^2.1.0",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/vuetify": "1.12.1",
"core-js": "^3.15.1",
"electron": "^10.1.5",
"electron-builder": "^22.9.1",
"glob": "^7.1.7",
"noty": "^3.2.0-beta",
"nuxt": "^2.15.7",
"nuxtron": "^0.3.1",
"sass": "1.32.13",
"swiper": "^5.4.5",
"prisma": "^3.0.2",
"vue-awesome-swiper": "^4.1.1"
}
}
The solution provided by Mojtaba Barari works but it results in #prisma packages being present in both resources/app/node_modules and resources/node_modules.
There is a better way how to do it:
{
"build": {
"extraResources": [
{
"from": "node_modules/.prisma/client/",
"to": "app/node_modules/.prisma/client/"
}
],
}
}
In this case, the Prisma client files will be copied directly to resources/app/node_modules where other #prisma packages are already present and so you will save ~ 10 MB compared to the other solution.
EDIT:
My previous solution doesn't work if an application is packaged into an asar archive. You need to use files field instead:
{
"build": {
"files": [
{
"from": "node_modules/.prisma/client/",
"to": "node_modules/.prisma/client/"
}
],
}
}
This is a universal solution which works even if you don't use an asar archive.
Ok, I finally solved it!!
first of all no need to change client generator output direction!
//schema.prisma
datasource db {
provider = "sqlite"
url = "file:../resources/database.db"
}
generator client {
provider = "prisma-client-js"
// output = "../resources/prisma/client" !! no need for this!
}
then in electron-builder config add ./prisma , #prisma and database
// my config file was a .yml
extraResources:
- "resources/database.db"
- "node_modules/.prisma/**/*"
- "node_modules/#prisma/client/**/*"
// or in js
extraResources:[
"resources/database.db"
"node_modules/.prisma/**/*"
"node_modules/#prisma/client/**/*"
]
this solved `Error: cannot find module : '.prisma/client'
but this alone won't read DB in built exe file!
so in main.js where importing #prisma/client should change DB reading directory:
import { join } from 'path';
const isProd = process.env.NODE_ENV === 'production';
import { PrismaClient } from '#prisma/client';
const prisma = new PrismaClient({
datasources: {
db: {
url: `file:${isProd ? join(process.resourcesPath, 'resources/database.db') : join(__dirname, '../resources/database.db')}`,
},
},
})
with these configs I could fetch data from my sqlite DB
My Jest config details are
jest.config.js
module.exports = {
transform: {
'^.+\\.svelte$': 'svelte-jester',
'^.+\\.js$': 'babel-jest',
},
moduleFileExtensions: ['js', 'svelte'],
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}
package.json
.
.
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"babel-jest": "^26.0.1",
"jest": "^26.0.1",
"svelte-jester": "^1.0.6",
"#testing-library/svelte": "^3.0.0"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack",
"dev": "webpack-dev-server --content-base public",
"test": "jest src",
"test:watch": "npm run test -- --watch"
},
.
.
I created src/test folder where my test.spec.js is as follows
import {fireEvent, render} from '#testing-library/svelte';
import App from '../App.svelte';
describe('test', () => {
test('Just a mock test', async () => {
const myMock = jest.fn();
console.log(myMock());
myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true);
console.log(myMock(), myMock(), myMock(), myMock());
});
});
Plz note that this I used a jest mock function just for testing purpose but whenever I import a svelte file as in this case App.svelte I get an error as below
FAIL src/test/test.spec.js
● Test suite failed to run
ParseError: Identifier is expected
I found a possible solution to this parsing error. Apparently, the IDE was unable to resolve certain style classes in the test.svelte file defined inside style tag, which is why it was showing up ParseError.
I would suggest anyone coming across this error to check your svelte file thoroughly for errors since svelte-testing-lib parses through the entire file before executing any test function.
I'm trying to get webpack to parse a javascript file that is using the new async/await syntax, but it keeps giving me a parsing error.
Here is my webpack.config.js file:
module.exports = {
entry: {
foo: './foo.js'
},
output: {
filename: 'webpack-compiled.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
My package.json file:
{
"name": "async-func-test",
"version": "1.0.0",
"description": "",
"main": "foo.js",
"scripts": {
"buildWithBabel": "babel foo.js --out-file babel-compiled.js",
"buildWithWebpack": "webpack --progress --colors"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-core": "^6.18.2",
"babel-loader": "^6.2.8",
"babel-plugin-syntax-async-functions": "^6.13.0",
"webpack": "^1.13.3"
}
}
My babel.rc file:
{
"plugins": [
"syntax-async-functions"
]
}
And the foo.js file:
async function asyncFunc() {
return 123
}
asyncFunc().then(x => console.log(x))
If I run the npm script 'buildWithBabel', it runs fine with no errors and creates the babel-compiled.js with the proper output.
However if I run the npm script 'buildWithWebpack', I get the following error message:
ERROR in ./foo.js
Module parse failed: C:\Users\Redark\Desktop\asyncFuncTest\node_modules\babel-loader\lib\index.js!C:\Users\Redark\Desktop\asyncFuncTest\foo.js Unexpected token (1:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:6)
I don't need to transform the async functions, just parse it. I'm not sure why it's not working for webpack as it should using the "syntax-async-functions" plugin in the .babelrc right?
You will need to use the transform-regenerator plugin as well, syntax-async-functions only allows Babel to parse the input (and then leave it alone). Webpack doesn't understand ES8 syntax yet, that's why it fails without having them transpiled.