Need to test SwiperJS component and jest throws an error - jestjs

this is what I have in my test file and have no idea how to fix it was searching everywhere could not find the solution
import { render } from '#testing-library/react';
import { ImageGallery } from '../index';
describe('Swiper has to render', () => {
test('Will Swiper render', () => {
const { asFragment } = render(<ImageGallery />);
expect(asFragment()).toMatchSnapshot();
});
});
having this in my test file
having an error
like that
● 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.
SyntaxError: Unexpected token 'export'
1 | /* eslint-disable import/no-unresolved */
2 | import React, { useState, useCallback } from 'react';
> 3 | import { Swiper, SwiperSlide } from 'swiper/react';
| ^
4 | import ImageViewer from 'react-simple-image-viewer';
5 |
6 | import 'swiper/css/bundle';
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/ImageGallery/ImageGallery.js:3:1)

Related

I get an error when testing with jest on code that imports a homegrown library

I get an error when testing with jest on code that imports a homegrown library.
Other than jest, the other processes are successful, how can I make the test succeed?
FAIL src/pages/e2e.spec.tsx
● Test suite failed to run
Cannot find module 'components/layout/Layout' from 'src/pages/index.tsx'
Require stack:
src/pages/index.tsx
src/pages/e2e.spec.tsx
> 1 | import { Layout } from 'components/layout/Layout'
| ^
2 | import { HomepageComponent } from 'components/parts/home'
3 | import { useSearchMedicines } from 'hooks/api/product/useSearchMedicines'
4 | import { useRouter } from 'next/router'
at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:427:11)
at Object.<anonymous> (src/pages/index.tsx:1:1)
at Object.<anonymous> (src/pages/e2e.spec.tsx:7:1)
try
commnad:
npm test
code
import { render, screen } from '#testing-library/react'
import userEvent from '#testing-library/user-event'
import { Layout } from 'components/layout/Layout'
import styled from '#emotion/styled'
import { Header } from 'components/parts/common/header'
import { useTranslationText } from 'locale'
import Home from './index'
describe('Home', () => {
it('should display search results', async () => {
// Render the Home component
render(<Home />)
// Search for a new keyword
const searchInput = screen.getByRole('textbox')
userEvent.clear(searchInput)
userEvent.type(searchInput, 'new keyword')
userEvent.click(screen.getByRole('button'))
// Wait for new search results to load
const newMedicineNames = await screen.findAllByTestId('medicine-name')
expect(newMedicineNames.length).greaterThan(0)
expect(newMedicineNames[0]).not.equal(medicineNames[0])
})
})
expect
test success
Test Suites: 0 failed, 1 passed, 1 total
Tests: 0 failed, 1 passed, 1 total

react-app-rewired, transformIgnorePatterns on Apollo Client 3

I have a React app with:
react-app-rewired
Apollo Client 3.5.5
I have an error when I try to use this import:
import { MockedProvider } from '#apollo/client/testing';
If I do console.log(MockedProviderenter code here) I got: undefined.
If in my jest config I add this:
"transformIgnorePatterns": ["<rootDir>/node_modules/.*"]
It works and I got the proper console.log: [Function: MockedProvider] { defaultProps: { addTypename: true } }
That's fine, yes, but I'm getting errors in other partes of the app, like:
SyntaxError: Invalid or unexpected token
4 | import Loader from 'react-loaders';
5 |
> 6 | import 'loaders.css/loaders.css';
So, what could I do?
I don't get how to apply that only for Apollo Client.

Why I can not use " import { createSlice, configureStore } from '#reduxjs/toolkit' " in Node.js

guys
I am learning redux, and try to run a very simple example code in node.js environment. I got the following error when I try to use :
import { createSlice, configureStore } from '#reduxjs/toolkit' .
The errors is:
import { createSlice, configureStore } from '#reduxjs/toolkit'
^^^^^^^^^^^
SyntaxError: Named export 'createSlice' not found. The requested module '#reduxjs/toolkit' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
If I use import like what the error tip says:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
All is OK.
What I want to ask is:
It gives me a wrong example in the official website of Redux? Or Just I run the example with a wrong way?
The following is the detail information.
My Node.js version is: v14.17.3
1 Init a node project:
mkdir redux_01
cd redux_01
yarn init
yarn add #reduxjs/toolkit
2 Modify the 'package.json', add a line in it:
"type":"module"
3 Create a file 'index.js' with the "Redux Toolkit Example" code parsed from https://redux.js.org/introduction/getting-started.
import { createSlice, configureStore } from '#reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))
// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
4 Now I run it like this:
node index.js
I then got that error message that I just mentioned.
The reason for the error is explained here:
https://lightrun.com/answers/reduxjs-redux-toolkit-cannot-import-redux-toolkit-from-a-nodejs-esm-module "here"
solution:
import * as toolkitRaw from '#reduxjs/toolkit';
const { createSlice,configureStore } = toolkitRaw.default ?? toolkitRaw;
or in Typescript:
import * as toolkitRaw from '#reduxjs/toolkit';

Unittesting with jest and IntelliJ

I get an error with a jest unittest in intellij, which I don't know how to solve.
Simple test:
import React from 'react';
import { render, screen } from '#testing-library/react';
import TestComponenent from "./tests/Testcomponent";
test('test TestComponent', () => {
render(<TestComponenent />);
expect(screen.getByText("test")).toBeInTheDocument();
});
When running this test in IntelliJ, I get the following error:
● Test suite failed to run
TypeError: Class constructor Spec cannot be invoked without 'new'
102 | function createdPatchedSpec(OriginalSpec, registry) {
103 | function PatchedSpec(attrs) {
> 104 | OriginalSpec.apply(this, arguments);
| ^
105 | if (attrs && attrs.id) {
106 | registry[attrs.id] = this;
107 | }
at new PatchedSpec (../../../../Program Files/JetBrains/IntelliJ IDEA 2018.3.4/plugins/JavaScriptLanguage/helpers/jest-intellij/lib/jest-intellij-jasmine.js:104:18)
at Object.<anonymous> (src/TestComponent.test.js:5:1)
Versions:
Jest Package : 3.4.1
Nodejs : 12.16.3
Can someone help ?
Solved: I installed the newest Version of IntelliJ.

Prerendering causes a SyntaxError: Cannot use import statement outside a module

I'm trying to execute prerender.ts as seen here to prerender my Angular code, but when I try and execute it using ts-node prerender.ts, I get the error:
import 'zone.js/dist/zone-node';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:892:18)
What is the proper way to execute this from NodeJS? Here is what prerender.ts looks like:
import 'zone.js/dist/zone-node';
import * as path from 'path';
import * as fs from 'fs';
import { enableProdMode } from '#angular/core';
import { renderModuleFactory } from '#angular/platform-server';
import { AppPrerenderModuleNgFactory } from './dist-prerender/main.bundle';
const distFolder = './dist';
const index = fs
.readFileSync(path.resolve(__dirname, `${distFolder}/index.html`), 'utf8')
.toString();
// we could automate this based on the app.routes.ts file but
// to keep it simple let's just create an array with the routes we want
// to prerender
const paths = [
'/about',
'/brews',
'/consultancy'];
enableProdMode();
// for every route render the html and save it in the correct folder
paths.forEach(p => renderToHtml(p, distFolder + p));
// don't forget to overwrite the index.html as well
renderToHtml('/index.html', distFolder);
function renderToHtml(url: string, folderPath: string): void {
// Render the module with the correct url just
// as the server would do
renderModuleFactory(AppPrerenderModuleNgFactory, {
url,
document: index
}).then(html => {
// create the route directory
if (url !== '/index.html') {
fs.mkdirSync(folderPath);
}
fs.writeFile(folderPath + '/index.html', html, (err => {
if (err) {
throw err;
}
console.log(`success`);
});
});
}
Update: I found that if I used tsc to transpile prerender.ts to JavaScript first and then executed that with node, I could get past this error. However, I started getting an error which I think is indicative of this code not running within the context of ngZone. So the code is still not right.
As stated here:
Current node.js stable releases do not support ES modules. Additionally, ts-node does not have the required hooks into node.js to support ES modules. You will need to set "module": "commonjs" in your tsconfig.json for your code to work.
Thus, pass below compiler option:
ts-node --compiler-options '{"module": "commonjs"}' prerender.ts
Of course, you can just include "module": "commonjs" in your (root) tsconfig.json file under "compilerOptions". This way you only have to execute:
ts-node prerender.ts

Resources