Jest encountered an unexpected token (TinyMCE) - css

I'm using Jest to run unit tests on one of my components, but I'm getting a few errors.
The component that I am trying to test uses tinymce and as a result, I import a few files from tinymce. I've seen on the offical Jest documentation that I insert the following, which I have in my setupTests.js file:
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
However, I have done that, but I am encountering another problem:
Jest encountered an unexpected token SyntaxError: Unexpected token '.'
import "tinymce/skins/ui/oxide.skin.min.css"
I have tried to follow the advice of mocking everything that comes from Tinymce, as well as mocking non-JS modules, using "moduleNameMapper". For example, my _jest.config.js file includes:
module.exports = {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
"module_name_(.*)": "<rootDir>/substituted_module_$1.js",
"assets/(.*)": [
"<rootDir>/images/$1",
"<rootDir>/photos/$1",
"<rootDir>/recipes/$1"
]
}
"transformIgnorePatterns": [
"<rootDir>/node_modules/"
]
}
The above doesn't work and I still get the same error.
EDIT:
As per one of the suggestions, I've created a styleMock.js file which contains module.exports = {}; and is included in my src/tests/jest/__mocks__ path. I've then inputted:
"moduleNameMapper": {
'\\.(css|less)$': '<rootDir>/src/tests/jest/__mocks__/styleMock.js'
}
But I'm still getting the same error as above.

Following this documentation worked.
In another words, adding in the package.json the following:
{
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "identity-obj-proxy"
}
}
}
As well as running yarn add --dev identity-obj-proxy

Related

`Module not found: Can't resolve 'fs'` when using near-api-js in Next.js

I have a Next.js app using near-api-js, and I'm getting this error.
It's confusing since I'm not using unencrypted_file_system_keystore anywhere.
error - ./node_modules/near-api-js/lib/key_stores/unencrypted_file_system_keystore.js:7:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/near-api-js/lib/key_stores/index.js
P.S. This question is specifically about using near-api-js. I'll update the answer when I learn of a better solution to this particular problem since there are known bugs in that library and my current answer below feels like a wonky workaround.
Changing the contents of /next.config.js to the following seemed to fix it for me:
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
future: {
webpack5: true, // By default, if you customize webpack config, they switch back to version 4. (backward compatibility?)
},
webpack(config) {
// eslint-disable-next-line no-param-reassign
config.resolve.fallback = {
...config.resolve.fallback,
fs: false, // https://stackoverflow.com/a/67478653/470749
};
return config;
},
};
Thanks to https://stackoverflow.com/a/67478653/470749!
But I bet there is a bug in near-api-js. I doubt this step by me should have been necessary.

Next JS Babel can't resolve 'module'

I've started to develop a multi-language web application with Next JS and Lingui.js
Lingui.js is using babel so I had to install it aswell.
I've followed this tutorial https://blog.logrocket.com/complete-guide-internationalization-nextjs/
After facing some issues i've also followed the official documentation of Lingui.js https://lingui.js.org/tutorials/setup-react.html
I faced a lot of issues with babel and typescript.
But now I struggle with following error, which I could not find any help with:
wait - compiling / (client and server)...
error - ./node_modules/resolve-from/index.js:3:0
Module not found: Can't resolve 'module'
Import trace for requested module:
./node_modules/import-fresh/index.js
./node_modules/cosmiconfig/dist/loaders.js
./node_modules/cosmiconfig/dist/index.js
./node_modules/babel-plugin-macros/dist/index.js
./node_modules/#lingui/macro/index.js
./src/pages/index.tsx
https://nextjs.org/docs/messages/module-not-found
false
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
at Home (webpack-internal:///./src/pages/index.tsx:36:51)
at I18nProvider (C:\Project\app\node_modules\#lingui\react\cjs\react.development.js:46:19)
at MyApp (webpack-internal:///./src/pages/_app.tsx:48:24)
at StyleRegistry (C:\Project\app\node_modules\styled-jsx\dist\index\index.js:671:34)
at AppContainer (C:\Project\app\node_modules\next\dist\server\render.js:394:29)
at AppContainerWithIsomorphicFiberStructure (C:\Project\app\node_modules\next\dist\server\render.js:424:57)
at div
at Body (C:\Project\app\node_modules\next\dist\server\render.js:701:21)
error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in,
or you might have mixed up default and named imports.
here is my babel.config.js
module.exports = {
presets: [
"#babel/preset-env",
"#babel/preset-react",
"#babel/preset-typescript"
],
plugins: [
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
],
[
"#babel/plugin-transform-react-jsx",
{
"runtime": "automatic"
}
],
[
'#babel/plugin-transform-runtime',
{
absoluteRuntime: false,
corejs: false,
helpers: true,
regenerator: true,
version: '7.0.0-beta.0',
},
'react-native-reanimated/plugin',
],
]
}
and my webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: ['babel-loader', 'ts-loader']
}
]
}
};
The part with React.jsx: type is invalid is because of getStaticProps in index.tsx.
So this might be an separate issue
Have you already tried the solution mentioned here ?
webpack.config.js
node: {
module: "empty",
}
I ended up deleting everything I had from Babel and lingui and copied all imports from another project which was running.
Cannot name the difference between them, but it worked afterwards.

Behavior change in speech-rule-engine 3.2?

I'm using the speech-rule-engine to generate English text from MathML. When trying to upgrade from v3.1.1 to v3.2.0 I'm seeing tests fail for reasons I don't understand.
I created a simple two file project that illustrates the issue:
package.json
{
"name": "failure-example",
"license": "UNLICENSED",
"private": true,
"engines": {
"node": "14.15.5",
"npm": "6.14.11"
},
"scripts": {
"test": "jest"
},
"dependencies": {
"speech-rule-engine": "3.2.0"
},
"devDependencies": {
"jest": "^26.6.3"
},
"jest": {
"notify": false,
"silent": true,
"verbose": true
}
}
example.test.js
const sre = require('speech-rule-engine');
beforeAll(() => {
sre.setupEngine({
domain: 'mathspeak'
});
});
test('simple single math', () => {
expect(JSON.parse(JSON.stringify(sre.engineSetup(), ['domain', 'locale', 'speech', 'style'])))
.toEqual({
locale: 'en',
speech: 'none',
style: 'default',
domain: 'mathspeak',
});
expect(sre.engineReady())
.toBeTruthy();
expect(sre.toSpeech('<math><mrow><msup><mn>3</mn><mn>7</mn></msup></mrow></math>'))
.toBe('3 Superscript 7');
});
Running npm install and npm run test results in a failure because SRE is returning 37 instead of 3 Superscript 7. Editing package.json to use v3.1.1 of the engine and rerunning results in a passing test.
Obviously something has changed, but I'm totally missing what I need to do to adapt. Has anyone else encountered this, or see what I clearly do not?
Problem solved, with the help of the maintainer of SRE. The problem is not in 3.2.0, but that jest does not wait for sre to be ready. The test was only correct by a fluke in 3.1.1 as the rules were compiled into the core. The following test fails with the above setup in 3.1.1 as well as the locale is not loaded:
expect(sre.toSpeech('<math><mo>=</mo></math>'))
.toBe('equals');
Expected: "equals"
Received: "="
The main reason is that jest fails to load the locale file. Setting "silent": false will show the error:
Unable to load file: /tmp/tests/node_modules/speech-rule-engine/lib/mathmaps/en.js
TypeError: Cannot read property 'readFileSync' of null
The reason for this error is that jest does not know that it runs in node. Adding:
"testEnvironment": "node",
to the jest configuration in package.json causes the expected behavior.

Did Firebase Cloud Functions ESLint change recently?

I created a cloud function project with firebase a few months ago, and used linting.
I recently created a new cloud function project with linting, and now the linter is complaining about random rules I never set. I don't remember it enforcing nearly the amount of style rules a few months ago.
Things like:
This line has a length of 95. Maximum allowed is 80
Missing JSDoc comment
Missing Trailing comma
expected indentation of 2 spaces but found 4
Strings must use singlequote
It's also not letting me use async/await.
I found out I can individually set these rules in my .eslintrc.js file, but that's annoying and I don't want to do that. By default, why aren't these rules disabled? I just want basic rules that make sure my code won't fail when run, not random style preferences like single/double quotes and max line length.
Is there any way to use just basic linting functionality with firebase functions?
I ran into the same issue as you. The new, more strict linting rules seem to come from the fact that Firebase functions use the "google" eslint base configuration plugin by default now. Read more about configuring ESLint plugins in the docs. My older Firebase functions were using tslint without issue.
Here's what my .eslintrc.js file looked like while I was getting style errors from eslint:
module.exports = {
env: {
es6: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
'google',
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: ['tsconfig.json', 'tsconfig.dev.json'],
sourceType: 'module',
},
ignorePatterns: [
'/lib/**/*', // Ignore built files.
],
plugins: ['#typescript-eslint', 'import'],
rules: {
quotes: ['error', 'double'],
},
};
I deleted 'google' from the extends property, which seemed to resolve almost all of the style linting issues.
Now it looks like this:
module.exports = {
env: {
es6: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:import/errors',
'plugin:import/warnings',
'plugin:import/typescript',
],
parser: '#typescript-eslint/parser',
parserOptions: {
project: ['tsconfig.json', 'tsconfig.dev.json'],
sourceType: 'module',
},
ignorePatterns: [
'/lib/**/*', // Ignore built files.
],
plugins: ['#typescript-eslint', 'import'],
rules: {
quotes: ['error', 'double'],
},
};
You can get rid of the google extends value but I would suggest keeping it and just turning off the rules that bother you the most, which for me is indentation and max length (of lines):
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
"quotes": ["error", "double"],
"indent": ["off"],
"max-len": ["off"],
},
};
For anyone who is confused by this, there is a lint config file in the Cloud Functions folder that you can edit. As of this answer, that file is named .eslintrc.js.

Angular 2 submodule routing with AOT and Rollup

What is the correct way to configure a submodule in Angular 2 so that it will work after AOT and rollup? I'm not concerned about lazy loading and will be happy for all submodules to be bundled together, but loadChildren is the cleanest way of referencing a submodule and having it use the correct <router-outlet>, and although I've tried various methods, none will work in both development and production.
I followed the instructions in the AOT cookbook to prepare my app for deployment. My module structure is root > account > admin, and I want the admin routes to load in the outlet defined by the account component.
Here's the router config for the account module:
import { NgModule } from '#angular/core';
import { AdminModule } from './admin/admin.module';
const accountRoutes: Routes = [{
path: 'account',
component: AccountComponent,
children: [
{ path: 'setup', component: SetupComponent },
{ path: 'admin', loadChildren: () => AdminModule }
]
}];
This works in development, but NGC compilation fails with Error: Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'accountRoutes'.
I added an export to accountRoutes but this also fails to compile with Error: Error encountered resolving symbol values statically. Function calls are not supported..
One suggestion was to use a string instead of a function so that NGC can compile the code:
loadChildren: 'app/account/admin/admin.module#AdminModule'
This works in development and compiles successfully but the compiled app will not run, because SystemJS is unavailable. The error is:
ERROR Error: Uncaught (in promise): TypeError: System.import is not a function
TypeError: System.import is not a function
at t.loadFactory (build.js:6)
at t.load (build.js:6)
at t.loadModuleFactory (build.js:12)
I tried including SystemJS in the production build but it could not find the separate module file app/account/admin/admin.module.ngfactory - after rollup everything is in one build.js. There may be a way to have separate rollups build each submodule, but that's a lot of work.
I found the suggestion of referring to an exported function:
export function loadAdminModule() {
return AdminModule;
}
loadChildren: loadAdminModule
This works in development, but in production the runtime compiler is unavailable so it logs build.js:1 ERROR Error: Uncaught (in promise): Error: Runtime compiler is not loaded.
The helper function can be modified so it works in production by referencing the NgFactory instead, but this won't work in development.
import { AdminModuleNgFactory } from '../../../aot/src/app/account/admin/admin.module.ngfactory';
export function loadAdminModule() {
return AdminModuleNgFactory;
}
loadChildren: loadAdminModule
Is there a supported way of using loadChildren so that it will work with the instructions in the AOT cookbook? Is it better to use webpack instead?
For anyone having the same problem, here's the temporary workaround I'm using. Hopefully a better answer will come along soon.
I now define my submodules in a dedicated file, submodules.ts. I have two versions of this file, submodules-jit.ts for development, and submodules-aot.ts for AOT/rollup deployment to production. I gitignore submodules.ts and have added commands to my npm start and npm build:aot scripts that substitute in the right one.
// submodules-jit.ts
import { AdminModule } from './account/admin/admin.module'
export function adminModule(): any { return AdminModule; }
// submodules-aot.ts
import { AdminModuleNgFactory } from '../../aot/src/app/account/admin/admin.module.ngfactory'
import { AdminModule } from './account/admin/admin.module'
export function adminModule(): any { return AdminModuleNgFactory; }
export function adminModuleKeep(): any { return AdminModule; }
AdminModule must be referenced in the AOT file so it is preserved.
Then I use the adminModule function in my routes:
import { adminModule } from '../submodules'
{ path: 'admin', loadChildren: adminModule }
Finally for convenience, npm scripts drop in the correct file.
"build:aot": "cp src/submodules-aot.ts src/app/submodules.ts && ngc -p tsconfig-aot.json && rollup -c rollup-config.js",
"start": "cp src/submodules-jit.ts src/app/submodules.ts && concurrently \"npm run build:watch\" \"npm run serve\""
Needless to say this is a horrible hack, but it keeps the routing files clean and most of the evil in one place.
In my case I solved with your hint on loading routes from an external module, then reading this issue on angular/cli issue page.
So, I came out refactoring my routes from:
import { TestModule } from './pathToModule/test.module';
export function exportTestModule() {
return TestModule;
}
. . .
{
path: 'test',
loadChildren: exportTestModule
}
To:
. . .
{
path: 'test',
loadChildren: './pathToModule#TestModule'
}

Resources