vue/cli-plugin-unit-jest cannot find module - node.js

I am using vue/cli-plugin-unit-jest and after setting it up accourding to the docs I keep getting this error:
Cannot find module '#antmedia/webrtc_adaptor' from 'src/components/player.vue'
Require stack:
src/components/player.vue
src/components/Dashboard.vue
src/views/Operation.vue
src/router/index.js
src/stores/modules/account.module.js
src/stores/index.js
tests/unit/cameras.spec.js
61 | import config from '../config/config'
62 | import { mapActions, mapState } from 'vuex'
> 63 | import { WebRTCAdaptor } from '#antmedia/webrtc_adaptor'
| ^
64 |
65 | export default {
66 | name: 'player',
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
at Object.<anonymous> (src/components/player.vue:63:1)
at Object.<anonymous> (src/components/Dashboard.vue:18:1)
When I remove line 63 the test begins to pass so obviously there is some issue with jest resolving the path but I can't find a solution.
This is the jest.config.js file:
module.exports = {
verbose: true,
preset: '#vue/cli-plugin-unit-jest',
ResolverOptions: {
paths: [
'<rootDir>/src'
]
}
}

This issue occurs because by default, jest doesn't transform anything from /node_modules.
What worked for me is this:
replace import { WebRTCAdaptor } from '#antmedia/webrtc_adaptor'
with import { WebRTCAdaptor } from '../../node_modules/#antmedia/webrtc_adaptor/src/main/webapp/js/webrtc_adaptor.js'
And in package.json add:
"jest" : {
"preset": "#vue/cli-plugin-unit-jest",
"transformIgnorePatterns": [
"/node_modules/(?!#antmedia).+\\.js$"
]
},
Of course replace #antmedia with the package you want to import.

Related

Switching Storybook from Webpack to Vita in Gatsby app

I work on a Gatsby project and I'm hoping to run our Storybook with Vita instead of our existing Webpack setup. I'm clearly not doing it right.
I added the plugins:
"#storybook/builder-vite": "^0.4.2",
"#vitejs/plugin-react": "^3.1.0",
"vite": "^4.1.1",
I also added our aliases by importing my tsconfigand converting the paths to the right format.
Although most of my attempts to run it resulted in about 1000 instances of
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
it's actually running now. And it booted up WAY faster than it used to.
The only issue appears to be that it's not reloading, not at all. I make a change in a component, or a change in a story, and there is zero output in the terminal running storybook.
Although I do notice that this run, although it looks like it's working in the browser, does still give only these two errors:
Failed to resolve dependency: react/jsx-runtime, present in 'optimizeDeps.include'
Failed to resolve dependency: react/jsx-dev-runtime, present in 'optimizeDeps.include'
How can I fix this? I'm so close!
I've tried...
const react = require('#vitejs/plugin-react');
//...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
// is this where this goes?
plugins: [
react({
jsxRuntime: 'classic',
}),
],
resolve: { alias: aliasPathsVite },
},
})
},
}
Which does open Storybook in the browser, but it doesn't load, and the terminal gives endless instances of:
10:30:38 AM [vite] Internal server error: Transform failed with 2 errors:
Typography/Links.tsx:3:4: ERROR: The symbol "prevRefreshReg" has already been declared
Typography/Links.tsx:4:4: ERROR: The symbol "prevRefreshSig" has already been declared
Plugin: vite:esbuild
File: Typography/Links.tsx:1:42
The symbol "prevRefreshReg" has already been declared
1 | import RefreshRuntime from "/#react-refresh";let prevRefreshReg;let prevRefreshSig;if (import.meta.hot) { if (!window.__vite_plugin_react_preamble_installed__) { throw new Error( "#vitejs/plugin-react can't detect preamble. Something is wrong. " + "See https://github.com/vitejs/vite-plugin-react/pull/11#discussion_r430879201" ); } prevRefreshReg = window.$RefreshReg$; prevRefreshSig = window.$RefreshSig$; window.$RefreshReg$ = (type, id) => { RefreshRuntime.register(type, "Typography/Links.tsx" + " " + id) }; window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;}var _jsxFileName = "Typography/Links.tsx";
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
| ^
4 | let prevRefreshSig;
5 | if (import.meta.hot) {
The symbol "prevRefreshSig" has already been declared
2 | import RefreshRuntime from "/#react-refresh";
3 | let prevRefreshReg;
4 | let prevRefreshSig;
| ^
5 | if (import.meta.hot) {
6 | if (!window.__vite_plugin_react_preamble_installed__) {
at failureErrorWithLog (node_modules/esbuild/lib/main.js:1604:15)
at node_modules/esbuild/lib/main.js:837:29
at responseCallbacks.<computed> (node_modules/esbuild/lib/main.js:701:9)
at handleIncomingPacket (node_modules/esbuild/lib/main.js:756:9)
at Socket.readFromStdout (node_modules/esbuild/lib/main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)
I've tried...
module.exports = {
// ...
async viteFinal(config) {
return mergeConfig(config, {
resolve: {
alias: {
...aliasPathsVite,
'react/jsx-runtime': path.join(
__dirname,
'node-modules/react/jsx-runtime'
),
},
optimizeDeps: {
include: ['react/jsx-runtime']
}
},
})
},
}
which opens a non-working Storybook in the browser, and the terminal says this hundreds of times
Failed to resolve import "react/jsx-dev-runtime" from "react/jsx-dev-runtime". Does the file exist?
Then some of these:
[vite] error while updating dependencies:
Error: ENOENT: no such file or directory, rename 'node_modules/.vite-storybook/deps_temp' -> 'node_modules/.vite-storybook/deps'
at renameSync (node:fs:1030:3)
at Object.commit (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42874:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async commitProcessing (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42348:17)
at async runOptimizer (file:///node_modules/vite/dist/node/chunks/dep-3007b26d.js:42386:17)
And then a bunch of issues importing CSS files, like this one
10:45:29 AM [vite] Internal server error: Failed to resolve import "./header.css" from "node_modules/#storybook/mdx1-csf/dist/esm/stories/Header.js?v=ec48b265". Does the file exist?
Have you tried something like this?
resolve: {
alias: {
'react/jsx-runtime': 'react/jsx-runtime.js',
},
},
Source: https://github.com/vitejs/vite/issues/6215
Also:
optimizeDeps.include: ['react/jsx-runtime']
Another way can be tweaking the configuration of #vitejs/plugin-react:
import react from '#vitejs/plugin-react';
export default defineConfig({
plugins: [
react({
jsxRuntime: 'classic',
}),
]
});

Jest test gives me "Cannot find module" when running tests, but the code compiles fine outside of tests. Whats up?

I am writing my first test for a large application using NestJS and TypeScript. I want to import an entity which imports an interface from a module in another folder. This is proving challenging.
The project has a structure like
apps
..apis
--..web-api
----..src
----..package.json
----..jest.config.js
------..app
--------..profiles
----------.._entities
------------..profile.entity.spec.ts <--- the test
------------..profile.entity.ts
libs
--app-interfaces
----src
------lib
--------profile
----------index.ts <--- the files the test is trying to import and test
----------gender.enum.ts
----------profile.interface.ts
In profile.entity.spec.ts I have:
import { ProfileEntity } from "./profile.entity";
import { GenderEnum, ProfileTypeEnum } from '../../../../../../../libs/app-interfaces/src/lib/profile';
// all that ../../ is what I have to do to get to the import and have it recognized in this .spec file
// it doesn't recognize the # symbol taking us to the root of the project
describe('Profile class', () => {
it('should make a profile with no fields', () => {
const profile = new ProfileEntity();
expect(profile).toBeTruthy();
});
});
and in profile.entity.ts:
import { Column, CreateDateColumn, DeleteDateColumn, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
import { GenderEnum, IProfile, ProfileTypeEnum } from '#ourProject/app-interfaces';
#Entity({ name: 'profile' })
export class ProfileEntity implements IProfile {
#PrimaryColumn({ nullable: false, unique: true })
id: string;
The profile.entity.ts file works fine when the app is compiled by Docker. However when I run my profile.entity.spec.ts file in Jest, I get:
Cannot find module '#ourProject/app-interfaces' from 'src/app/profiles/_entities/profile.entity.ts' // <--- this is a big clue
Require stack:
src/app/profiles/_entities/profile.entity.ts
src/app/profiles/_entities/profile.entity.spec.ts
1 | import { Column, CreateDateColumn, DeleteDateColumn, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';
> 2 | import { GenderEnum, IProfile, ProfileTypeEnum } from '#ourProject/app-interfaces';
| ^
3 |
4 |
5 | #Entity({ name: 'profile' })
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
at Object.<anonymous> (src/app/profiles/_entities/profile.entity.ts:2:1)
Is there some special configuration I need to use in jest.config.js to give jest testing access to files outside of the top lvl of the package.json?
here is jest.config.js
module.exports = {
displayName: 'web-api',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/apps/web-api',
roots: ['../../'],
};
The line Cannot find module '#ourProject/app-interfaces' from 'src/app/profiles/_entities/profile.entity.ts' does not occur when the file runs normally.
Let's say your tsconfig.json alias configuration looks like this:
"paths": {
"#ourProject/*": ["./libs/*"],
}
Then you would need to add a moduleNameMapper line in jest.config.js:
{
moduleNameMapper: {
'^#ourProject/(.*)$': ['<rootDir>/libs/$1'],
},
}
I didn't have an issue with aliased imports being in a different folder, but jest didn't recognize aliases defined in tsconfig.json.

Vite with Jest: cannot find module start with alias '#'

I'm using Jest in Vite. It works until I import a module from node_module.
import { defineComponent } from 'vue'
import { useCookies } from '#vueuse/integrations/useCookies'
I got this error.
FAIL src/components/MyComponent/index.test.ts
● Test suite failed to run
Cannot find module '#vueuse/integrations/useCookies' from 'src/components/MyComponent/index.vue'
Require stack:
src/components/MyComponent/index.vue
src/components/MyComponent/index.test.ts
16 | <script lang="ts">
17 | import { defineComponent } from 'vue'
> 18 | import { useCookies } from '#vueuse/integrations/useCookies'
| ^
19 |
20 | export default defineComponent({
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:306:11)
I guess somehow Jest cannot resolve the module starts with '#'. Maybe I should write a moduleNameMapper? I also tried to install vite-jest, but somehow my app just crash, maybe I mess up something.
Anyway, thanks for your time, and if you need more information like my jest.config.js or vite.config.ts, please let me know.
Thank you.
Use moduleNameMapper in your jest.config.js file like following:
module.exports = {
//...
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
},
};
Also, if you are using TypeScript, you should add the following to your tsconfig.json file as well:
{
"compilerOptions": {
"paths": {
"#/*": ["./src"]
}
}
}

Jest return error when using "import * as .."

I have problems to run my test suite when I used import * as './filename.js' with Jest.
All the others imports run without problems so I don't think is a problem with babel configuration.
I use Nextjs 10(so react17), Jest, Typescript and babel-jest.
Here is my babel.config.js
{
"env": {
"development": {
"presets": ["next/babel"]
},
"production": {
"presets": ["next/babel"]
},
"test": {
"presets": [
[
"next/babel",
{
"preset-env": {
"modules": "commonjs"
}
}
]
]
}
}
}
And here an example of the test that gives the error:
import React, { FC, useEffect } from 'react'
import Head from 'next/head'
import Header from '../Header/Header'
import HeaderHome from '../HeaderHome/HeaderHome'
import Footer from '../Footer/Footer'
import styles from './Layout.module.css'
import * as settingsHelper from '../../helpers/_settingsHelper'
// .... normal react component here.
And inside the _seetingsHelper.js I call my cookieHelper like so:
import * as cookieHelper from './_cookies'
function initialise () {
// body of function here
}
error:
.../helpers/_settingsHelper.js:2
import * as cookieHelper from './_cookies'
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import styles from './Layout.module.css'
7 |
> 8 | import * as settingsHelper from '../../helpers/_settingsHelper'
| ^
9 |
10 | // prettier-ignore
11 | interface LayoutProps {
Someone already encountered this issue?

Why decorators won't work in Jest with Babel?

I'm trying to get JavaScript decorators to work using Jest and Babel:
./package.json
[...]
"devDependencies": {
[...]
"#babel/core": "7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/plugin-proposal-decorators": "^7.3.0",
"#babel/preset-env": "^7.3.1",
[...]
"jest": "^24.1.0"
},
[...]
"scripts": {
[...]
"jest --no-cache --verbose --config ./test/unit/jest.json"
}
./test/unit/.babelrc
{
"presets": [
[
"#babel/preset-env", {
"targets": {
"node": "current"
},
"modules": "commonjs",
"loose": true,
"debug": true
}
]
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true}]
]
}
./test/unit/jest.json
{
"modulePaths": [
"<rootDir>/../../src",
"<rootDir>/../../node_modules"
],
"moduleFileExtensions": [
"js",
"json"
],
"testRegex": "\\.spec\\.js$",
"setupFiles": [
"<rootDir>/jest.js"
],
"testEnvironment": "node"
}
./test/unit/jest.js
import 'aurelia-polyfills';
import {Options} from 'aurelia-loader-nodejs';
import {globalize} from 'aurelia-pal-nodejs';
import * as path from 'path';
Options.relativeToDir = path.join(__dirname, '../../src');
globalize();
When I run yarn test I get:
yarn run v1.12.3
$ jest --no-cache --verbose --config ./test/unit/jest.json
#babel/preset-env: `DEBUG` option
Using targets:
{
"node": "11.9"
}
Using modules transform: commonjs
Using plugins:
syntax-async-generators { "node":"11.9" }
syntax-object-rest-spread { "node":"11.9" }
syntax-json-strings { "node":"11.9" }
syntax-optional-catch-binding { "node":"11.9" }
Using polyfills: No polyfills were added, since the `useBuiltIns` option was not set.
console.error internal/process/next_tick.js:81
{ SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
at Parser.raise ([...]/node_modules/#babel/parser/lib/index.js:3831:17)
at Parser.expectOnePlugin ([...]/node_modules/#babel/parser/lib/index.js:5158:18)
at Parser.parseDecorator ([...]/node_modules/#babel/parser/lib/index.js:7428:10)
at Parser.parseDecorators ([...]/node_modules/#babel/parser/lib/index.js:7410:30)
at Parser.parseStatement ([...]/node_modules/#babel/parser/lib/index.js:7245:12)
at Parser.parseBlockOrModuleBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7812:25)
at Parser.parseBlockBody ([...]/node_modules/#babel/parser/lib/index.js:7799:10)
at Parser.parseTopLevel ([...]/node_modules/#babel/parser/lib/index.js:7181:10)
at Parser.parse ([...]/node_modules/#babel/parser/lib/index.js:8660:17)
at parse ([...]/node_modules/#babel/parser/lib/index.js:10643:38)
pos: 362,
loc: Position { line: 10, column: 0 },
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
console.log test/unit/resources/elements/price.spec.js:25
SyntaxError: [...]/src/resources/elements/product/price.js: Support for the experimental syntax 'decorators-legacy' isn't currently enabled (10:1):
8 | import { DataService } from 'services';
9 |
> 10 | #inject(Element, Store, DataService, EventAggregator, I18N)
| ^
11 | #useViewStrategy(new RemoteViewStrategy())
12 | export class ProductPrice {
13 |
FAIL test/unit/resources/elements/price.spec.js (5.467s)
ProductPrice
✕ should render current (5008ms)
● ProductPrice › should render current
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
18 | });
19 |
> 20 | it('should render current', done => {
| ^
21 | component.create(bootstrap).then(() => {
22 | const currentElement = document.querySelector('.current');
23 | expect(currentElement.innerHTML).toBe('');
at Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:92:20)
at Suite.it (resources/elements/price.spec.js:20:5)
● ProductPrice › should render current
Cannot call ComponentTester.dispose() before ComponentTester.create()
27 |
28 | afterEach(() => {
> 29 | component.dispose();
| ^
30 | });
31 | });
at ComponentTester.Object.<anonymous>.ComponentTester.dispose (../../node_modules/aurelia-testing/dist/commonjs/component-tester.js:66:19)
at Object.dispose (resources/elements/price.spec.js:29:19)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.389s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
What I'm doing wrong?
A good hint comes with the error message:
[...]
missingPlugin: [ 'decorators-legacy', 'decorators' ],
code: 'BABEL_PARSE_ERROR' }
The Babel integration of Jest tooks the .babelrc in the first place, for every other file reached from the test it searched only in the project root. In this case the Babel configuration was in ./test/unit.
So putting .babelrc into the project root folder is one possible fix (but not the best). More approaches can be found here.

Resources