CommonJS require won't work inside Jest test file - javascript

I am testing my backend with Jest, but I keep getting this error
\node_modules\generate-key\lib\generate.coffee:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){rn = (max) ->
^
SyntaxError: Unexpected token '>'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (node_modules/generate-key/index.js:2:18)
This is my jest config file:
module.exports = { clearMocks: true, coverageDirectory: 'coverage', testEnvironment: 'node',moduleFileExtensions: ['ts', 'js', 'json', 'node'] };
My test file:
/* eslint-disable no-undef */
const { getConvertedKind } = require('../common');
test('check', () => {
expect(3).toBe(3);
});
The imported function:
exports.getConvertedKind = kind => {
const kinds = {
cinemaPass: 'cinema',
hotelPass: 'hotel',
boardingPass: 'flight',
coupon: 'coupon',
eventTicket: 'event',
transit: 'transit',
storeCard: 'wallet',
offer: 'offer'
};
return kinds[String(kind)] || null;
};
package.json:
"scripts": {
"start": "nodemon server.js",
"start:prod": "NODE_ENV=production nodemon server.js",
"debug": "ndb server.js",
"test": "jest --config ./jest.config.js"
}

It seems like you're trying to load a .coffee file and by default jest doesn't transform node_modules.
You can check the transformIgnorePatterns option and try something like:
transformIgnorePatterns: ["node_modules/(?!generate-key)"],

Related

how add coffeescript in svelte on Rails 7?

I have a Rails 7 app with esbuild :
esbuild.config.js :
#!/usr/bin/env node
const watch = process.argv.includes("--watch");
const esbuild = require('esbuild')
const coffeeScriptPlugin = require('esbuild-coffeescript');
const esbuildSvelte = require('esbuild-svelte');
const sveltePreprocess = require('svelte-preprocess');
esbuild
.build({
entryPoints: ["app/javascript/all.js"],
bundle: true,
outfile: "app/assets/builds/all.js",
// outdir: "app/assets/builds/",
plugins: [
esbuildSvelte({
preprocess: sveltePreprocess({coffeescript: { bare: true }}),
}),
// coffeeScriptPlugin({bare: true}), I TRIED THIS TOO...
],
logLevel: "debug",
watch: watch
})
.catch(() => process.exit(1));
my.svelte :
<script lang="coffee">
test = ->
console.log 'test coffee'
test()
</script>
got an error :
$ yarn build --watch yarn run v1.22.19 $ node ./esbuild.config.js
--watch ✘ [ERROR] [plugin esbuild-svelte] Unexpected token
app/javascript/all.js:3:3:
3 │ 1:
╵ ^
2: <script lang="coffee">
3: test = ->
^
4: console.log 'test coffee'
5: test()
The plugin "esbuild-svelte" was triggered by this import
app/javascript/svelte_src.js:6:32:
6 │ import DemoSvelteComponent from './svelte/DemoSvelteComponent.svelte'
╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error [watch] build finished, watching for changes... error Command
failed with exit code 1. info Visit
https://yarnpkg.com/en/docs/cli/run for documentation about this
command.
$ node -v
v18.4.0
package.json :
{
"name": "app",
"private": "true",
"dependencies": {
"#hotwired/stimulus": "^3.0.1",
"#hotwired/turbo-rails": "^7.1.3",
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.1.0",
"esbuild-svelte": "^0.7.1",
"sass": "^1.52.3",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
},
"scripts": {
"build": "node ./esbuild.config.js"
}
}
How add coffeescript in svelte with Rails ?
This setup works with node v18.4.0 v16.15.1 v14.19.3. It turned out pretty much identical to what you have, except I don't know what's in your all.js file.
// package.json
{
"name": "app",
"private": "true",
"dependencies": {
"#hotwired/stimulus": "^3.0.1",
"#hotwired/turbo-rails": "^7.1.3",
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.0.0",
"esbuild-svelte": "^0.7.1",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
},
"scripts": {
"build": "node ./esbuild.config.js"
}
}
// esbuild.config.js
const watch = process.argv.includes("--watch");
const esbuild = require("esbuild");
const esbuildSvelte = require("esbuild-svelte");
const sveltePreprocess = require("svelte-preprocess");
esbuild
.build({
entryPoints: ["app/javascript/all.js"],
outdir: "app/assets/builds/",
bundle: true,
sourcemap: true,
plugins: [
esbuildSvelte({
preprocess: sveltePreprocess(),
}),
],
logLevel: "debug",
watch: watch,
})
.catch(() => process.exit(1));
// app/javascript/all.js
import App from "./my.svelte";
new App({ target: document.body });
<!-- app/javascript/my.svelte -->
<script lang="coffee">
test = ->
console.log 'test coffee'
test()
</script>
Compiles:
$ yarn build --watch
yarn run v1.22.19
$ node ./esbuild.config.js --watch
[watch] build finished, watching for changes...
[watch] build started (change: "app/javascript/my.svelte")
[watch] build finished
and shows up in the browser console:
test coffee my.svelte:1
This is a smaller working example, maybe it'll help eliminate the source of the error. It compiles my.svelte file directly and prints out the source.
// package.json
{
"dependencies": {
"esbuild": "^0.14.43",
"esbuild-coffeescript": "^2.1.0",
"esbuild-svelte": "^0.7.1",
"svelte": "^3.48.0",
"svelte-preprocess": "^4.10.7"
}
}
// esbuild.config.js
require("esbuild").build({
entryPoints: ["app/javascript/my.svelte"],
plugins: [require("esbuild-svelte")({ preprocess: require("svelte-preprocess")() })],
}).catch(() => process.exit(1));
$ node --version
v18.4.0
$ node ./esbuild.config.js
import { SvelteComponent, init, safe_not_equal } from "svelte/internal";
function instance($$self) {
var test;
test = function() {
return console.log("test coffee");
};
test();
return [];
}
class My extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, null, safe_not_equal, {});
}
}
export default My;
I don't find the problem, I make new app and copy files, I don't see when exactly that works, but that works ... ^^
May be a bad invisible character was in file?
So It's works fine with include esbuild-coffeescript ...
That stay a mystery for my use case (I try checkout from git and bug don't come back.... realy strange)
I've met the same problem in my rails app and my solution was using another build script
old:
"build-es": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets"
new:
"build": "node ./esbuild.config.js",

Module not found: Can't resolve 'fs

I'm trying to use useDapp and pinata SDK in my next js application.
My package.json file looks like this:
"name": "eternity",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#pinata/sdk": "^1.1.23",
"#usedapp/core": "^0.10.0",
"antd": "^4.18.5",
"next": "12.0.9",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "8.8.0",
"eslint-config-next": "12.0.9"
}
}
The useDapp is working fine but when I try to use pinata api, I get errors. I ran a very basic test code like this:
import pinataSDK from "#pinata/sdk";
const pinataTest = () => {
const pinata = pinataSDK(
"5d349f3841ee16d7e668",
"a6f32583de5736824a606746f0b9b9bc365a5c81b3d1c9f1a98822a39ddfbb6d"
);
pinata
.testAuthentication()
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
};
export default pinataTest;
It is just a test code given in the official docs of pinata SDK. But I run into this error.
https://nextjs.org/docs/messages/module-not-found
wait - compiling...
error - ./node_modules/#pinata/sdk/lib/pinata-sdk.js:24051:0
Module not found: Can't resolve 'fs'
Possible solutions to this error have been proposed here:
Module not found: Error: Can't resolve 'fs' in
The solutions that seems to be working for me is modifying my next.config.js file like this:
module.exports = {
reactStrictMode: true,
externals: {
FileReader: "FileReader",
},
webpack5: true,
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = { fs: false };
}
return config;
},
};
It seems to have solved the 'fs not found error, but then I run into this next error:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
error - ./node_modules/js-sha3/src/sha3.js:21:0
Module not found: Can't resolve 'process'
Import trace for requested module:
./node_modules/#ethersproject/keccak256/lib.esm/index.js
./node_modules/#ethersproject/abi/lib.esm/interface.js
./node_modules/#ethersproject/abi/lib.esm/index.js
./node_modules/#usedapp/core/dist/esm/src/constants/abi/index.js
./node_modules/#usedapp/core/dist/esm/src/constants/index.js
./node_modules/#usedapp/core/dist/esm/src/index.js
./pages/_app.js
It seems like the #useDapp module is not working without 'fs'.
Is there a way to solve this? Or am I missing something fundamental while using useDapp and pinata SDK in my next js app.

Next.js create a polyfill.js file in dist folder

I try to implement the Trading view library's next.js example.
In _document.js file I have to import
<script src="/static/datafeeds/udf/dist/polyfills.js" />
<script src="/static/datafeeds/udf/dist/bundle.js" />
But when I go to datafeeds/udf.dist folder only I can see is the bundle.js file.
And inside the udf folder I have this package.json file
{
"private": true,
"dependencies": {
"tslib": "2.1.0"
},
"devDependencies": {
"#rollup/plugin-node-resolve": "~9.0.0",
"rollup": "~2.28.2",
"rollup-plugin-terser": "~7.0.2",
"typescript": "4.2.3"
},
"scripts": {
"compile": "tsc",
"bundle-js": "rollup -c rollup.config.js",
"build": "npm run compile && npm run bundle-js"
}
}
and rollup.config.js
/* globals process */
import { terser } from 'rollup-plugin-terser';
import { nodeResolve } from '#rollup/plugin-node-resolve';
const environment = process.env.ENV || 'development';
const isDevelopmentEnv = (environment === 'development');
export default [
{
input: 'lib/udf-compatible-datafeed.js',
output: {
name: 'Datafeeds',
format: 'umd',
file: 'dist/bundle.js',
},
plugins: [
nodeResolve(),
!isDevelopmentEnv && terser({
ecma: 2017,
safari10: true,
output: { inline_script: true },
}),
],
},
];
When I run compile,bundle-js, and build scripts that only create the bundle.js file only. How can I create a polyfills.js file inside the dist folder? I hope this can be done with rollup pakcage.

Jest tests crashing due to ES6/Es.next Syntax

I'm trying to do some simple snapshot testing with jest and enzyme—moving to react-testing-library—for some react components that I am building.
When I run my tests the output contains a number of errors pointing to ES6/7 class properties.
My assumption was that I was missing babel-jest. I have followed the instructions to set that up but I am still receiving a number of errors from different components referring to a missing the babel transform...
See below:
Example Test:
import React from 'react';
import { render } from 'react-testing-library';
import HRWrapper from '.';
test('<HRWrapper> snapshot', () => {
const { container } = render(<HRWrapper>P.Body AaBbCc</HRWrapper>);
expect(container.firstChild).toMatchSnapshot();
});
Example Error:
● Test suite failed to run
.../packages/Tooltip/src/index.js: Missing class properties transform.
126 |
127 | class ToolTip extends React.Component {
> 128 | state = {
| ^
129 | active: false,
130 | style: {}
131 | }
Here is my configuration:
package.json:
{
...
"scripts": {
"postinstall": "npm run bootstrap",
"bootstrap": "lerna bootstrap",
"build": "lerna exec -- node ../../scripts/build.js",
"clean": "lerna clean",
"predev": "npm run alias",
"dev": "NODE_ENV=development start-storybook -p 9001 -c .storybook",
"docs": "for f in packages/*; do react-doc-generator $f/src -o $f/docs/README.md -e [*.story.js]; done",
"publish": "lerna --no-verify-registry publish",
"start": "npm run dev",
"test": "jest --json --outputFile=.jest-test-results.json",
"test:update": "jest --updateSnapshot",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint .",
"fix": "eslint --fix",
"alias": "node scripts/alias.js"
},
"repository": {
"type": "git",
...
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
jest.config.js:
module.exports = {
"setupTestFrameworkScriptFile": "<rootDir>/config/setup-test.js",
"moduleNameMapper": {
[`#myLibrary/(.*)$`]: "<rootDir>/packages/$1/src"
},
"transform": {
"^.+\\.jsx?$": "babel-jest"
},
};
setup-test.js:
// this is the jest setupTestFrameworkScriptFile
/*
* use mocked classNames instead of unique hashed className generated by
* styled-components for snapshot testing
*/
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-styled-components';
configure({ adapter: new Adapter() });
// here we set up a fake localStorage because jsdom doesn't support it
// https://github.com/tmpvar/jsdom/issues/1137
if (!window.localStorage) {
window.localStorage = {};
Object.assign(window.localStorage, {
removeItem: function removeItem(key) {
delete this[key];
}.bind(window.localStorage),
setItem: function setItem(key, val) {
this[key] = String(val);
}.bind(window.localStorage),
getItem: function getItem(key) {
return this[key];
}.bind(window.localStorage),
});
}
It's possible you also need stage-2 or stage-0.
See: https://github.com/tc39/proposals
Also remember that plugins are applied BEFORE presets, and presets are applied in order of last to first.
My colleague spotted the issue, one of those obvious ones staring me in the face...
transform-class-properties was missing from the plugins in my test environment configuration in my .babelrc.
I made the following changes and it now works properly.
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-class-properties", "transform-es2015-modules-commonjs"]
}
}

Jest test 'unexpected token export'

I'm trying to get my jest tests to run. I am getting the error SyntaxError: Unexpected token export at the line export default configureStore..specifically on the word 'export'. To me this suggests redux-mock-store is not being transpiled by Babel, so how can I force this with Jest? I'm using jest-webpack.
ContractsActions.test.js
import * as contractsActions from './contractsActions';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
const store = mockStore({})
return store.dispatch(contractsActions.fetchAllContracts()).then(() => {
//Do something
})
});
package.json
...
"scripts": {
"test": "jest-webpack",
...
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
...
webpack.config.js
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015', 'react', 'stage-2']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
}
},
I ended up fixing this problem by creating a separate .babelrc file, instead of trying to set the babel configuration settings in package.json. I'm sure there are other steps I tried that may have contributed but this seemed to be the one that fixed it.
.babelrc
{
"presets": [["es2015", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Take a look at the package.json from that package:
https://github.com/arnaudbenard/redux-mock-store/blob/master/package.json
You can see it offers different entry points:
"main": "dist/index-cjs.js",
"module": "dist/index-es.js",
"js:next": "dist/index-es.js",
"browser": "dist/index.min.js",
Check if your node_modules/redux-mock-store has a dist folder. If not, start the build that suits your requirements (also listed in package.json):
"build:cjs": "babel src --out-file dist/index-cjs.js",
"build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f umd -c -i src/index.js -o dist/index-umd.js",
"build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -f umd -c -i src/index.js -o dist/index-umd.min.js",
"build:es": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f es -c -i src/index.js -o dist/index-es.js",
"build": "npm run build:umd && npm run build:umd:min && npm run build:es && npm run build:cjs",
I don't know which of those versions buildable would be the right one for you, but I assume one of them will be. At worst, start npm i && npm run build:cjs in node_modules/redux-mock-store and resort to CommonJS require syntax:
const configureMockStore = require('redux-mock-store/dist/index-cjs.js');
Really hope this solves your problem, at least these are the steps I would try.

Categories

Resources