Invalid return value in simple jest test - jestjs

I am testing a view for Home component for React Native 0.68.2/jest 29.0. The simple test case is copied from jest doc:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { render, cleanup, screen, fireEvent } from "#testing-library/react-native";
import App from '../App';
describe ('App ', () => {
//afterEach(cleanup);
test ('shall stack screens', async () => {
const component = (<NavigationContainer>
<App />
</NavigationContainer>);
const {getByText} = render(component);
await waitFor(() => getByText('AppSplash'));
})
})
Here is the App.js:
import React, {useState, useContext, Component} from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import SplashScreen from './src/components/splashscreen/SplashScreen';
import SysError from './src/components/app/SysError';
import Bye from "./src/components/app/Bye";
import Verif1 from './src/components/signup/Verif1';
import Signup from './src/components/signup/Signup';
import TermCondition from './src/components/common/TermCondition';
import AppScreen from "./src/components/app/AppScreen";
const Stack = createStackNavigator();
export default function App() {
return (
<SafeAreaProvider>
<NavigationContainer>
<Stack.Navigator InitialRouteName="AppSplash">
<Stack.Screen name="AppSplash" component={SplashScreen} options={{headerShown:false}}/>
<Stack.Screen name="AppSysError" component={SysError} options={{headerShown:false}} />
<Stack.Screen name="AppScreen" component={AppScreen} options={{headerShown:false}} />
<Stack.Screen name="AppVerif1" component={Verif1} options={{headerShown:false}} />
<Stack.Screen name="AppSignup" component={Signup} options={{headerShown:false}} />
<Stack.Screen name="TermCondition" component={TermCondition} options={{headerShown:false}} />
<Stack.Screen name="Bye" component={Bye} options={{headerShown:false}} />
</Stack.Navigator>
</NavigationContainer>
</SafeAreaProvider>
);
};
Here is the output of yarn jest.
● Invalid return value:
`process()` or/and `processAsync()` method of code transformer found at
"/Users/macair/Documents/code/js/xyz_app6/node_modules/react-native/jest/assetFileTransformer.js"
should return an object or a Promise resolving to an object. The object
must have `code` property with a string of processed code.
This error may be caused by a breaking change in Jest 28:
https://jestjs.io/docs/upgrading-to-jest28#transformer
Code Transformation Documentation:
https://jestjs.io/docs/code-transformation
I just started using jest and none of solutions found this error works.

The error process() or/and processAsync() method of code transformer found at indicates that the issue is jest v28.x doesn't support react-native v68.x. You will either need to downgrade to jest v27.x or upgrade to react-native v70.x.
See this commit on the react-native github: https://github.com/facebook/react-native/commit/b5ff26b0b97d6cd600bdb9c33af866971ef14f9c
Jest 28 removed support for returning a string in the process method of a transformer (https://jestjs.io/docs/upgrading-to-jest28#transformer).
This PR changes assetFileTransformer to return an object instead of a string.
The above commit is a fix for the issue you are seeing. It was merged in. If you look closely at the commit message, underneath which you will find a list of tags associated with the commit. These tags will tell you which releases contain this commit.
The commit message shows the below tags.
v0.70.1 v0.70.0 v0.70.0-rc.4 v0.70.0-rc.3 v0.70.0-rc.2 v0.70.0-rc.1 v0.70.0-rc.0 latest
These tags tell us that the commit first made it into the 0.70 release candidate, eventually landing in the 0.70 stable release. It is also present, as you'd expect, in the 0.70.1 stable.
See for more info on releases https://reactnative.dev/contributing/release-faq
Either upgrade to react-native 70.x or downgrade Jest to 27.x.

Related

Npm build using Cloudflare Pages results in 'Cannot Find Module'

i'm trying to upload my create-react-app site to Cloudflare Pages, and everything's been going great, However, when I add this line: import NotFoundPage from "pages/NotFound.js"; of code to my App.js, it throws a rather odd error:
22:57:43.995 Failed to compile.
22:57:43.996
22:57:43.996 ./src/App.js
22:57:43.996 Cannot find module: 'pages/NotFound.js'. Make sure this package is installed.
22:57:43.996
22:57:43.996 You can install this package by running: npm install pages/NotFound.js.
What makes this even more confusing, is the code right above it works completely fine:
import PrivacyPolicyPage from "pages/PrivacyPolicy.js";
import TermsOfUsePage from "pages/TermsOfUse.js";
import NotFoundPage from "pages/NotFound.js";
Is anyone aware of why this is happening, and most importantly, why the app is building on my home environment (Windows 11) and not Cloudflare Pages?
The code of NotFound.js:
import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import ScrollToTop from 'components/ScrollToTop';
import NotFound from 'components/NotFound';
import Sidebar from 'components/Sidebar';
import Navbar from 'components/Navbar';
import Footer from 'components/Footer';
function NotFoundPage() {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => {
setIsOpen(!isOpen);
};
return (
<>
<Helmet>
<link rel="stylesheet" href="/css/notfound.css" />
</Helmet>
<ScrollToTop />
<Sidebar isOpen={isOpen} toggle={toggle} />
<Navbar noFade toggle={toggle} />
<NotFound />
<Footer sticky />
</>
);
}
export default NotFoundPage;
And App.js:
import React from "react";
import "App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from "pages";
import PrivacyPolicyPage from "pages/PrivacyPolicy.js";
import TermsOfUsePage from "pages/TermsOfUse.js";
import NotFoundPage from "pages/NotFound.js";
function App() {
return (
<Router>
<Switch>
<Route path="/" component={Home} exact />
<Route path="/privacy-policy" component={PrivacyPolicyPage} exact />
<Route path="/terms-of-use" component={TermsOfUsePage} exact />
<Route component={NotFoundPage} />
</Switch>
</Router>
);
}
export default App;
NOTE: I have tried it with ./ at the start of the import string, tried adding {} around the import object, and neither of those work either, throwing the same error. npm build with Browserify - Error: Cannot find module did not help.
Thank you to anyone who can help.
I managed to fix the issue by (and I know how odd this sounds) renaming the pages directory to page. My guess is that Cloudflare is doing some weird stuff with that, but I can't really be sure.

Deploying NextJS project to my own server (npm run build triggers module not found error)

I have built a NextJS project and I'm ready to deploying it to a staging server for testing (running AlmaLinux 8). I have installed node version 16.8.0.
I've copied the entire contents of my project to my server and run npm run build but I then get the error:
build
> next build
info - Loaded env from /var/www/html/CrashCatch/CrashCatchDocs_Testing/.env
Failed to compile.
./pages/[...].tsx:2:23
Type error: Cannot find module '../components/TopHeader' or its corresponding type declarations.
1 | import Head from 'next/head'
> 2 | import TopHeader from "../components/TopHeader";
| ^
3 | import Link from 'next/link'
4 | import {useRouter} from "next/router";
5 | import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
Below is a screenshot showing the directory structure
In the `./pages[...].tsx I have the following
import Head from 'next/head'
import {getSlugFromUrl} from "../JSFuncs/HelperFunctions";
import UserHelpContainer from "../components/Articles/UserHelpContainer";
import UserSidebar from "../components/Sidebar/UserSidebar";
import useArticle from "../hooks/useArticle";
import {useEffect, useState} from "react";
import useCrashCatch from "../hooks/useCrashCatch";
import TopHeader from "../components/TopHeader";
export default function Home() {
const slug = getSlugFromUrl();
const {loading, publishedArticle, errors, refetch} = useArticle(slug);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const {crashcatch} = useCrashCatch('12345', "123456", "1.0.0");
useEffect(() => {
(
async function() {
await refetch();
}
)();
}, [slug]);
return (
<>
<div className="w-full h-full min-h-full overflow-none absolute">
<Head>
<title>Crash Catch Documentation</title>
<link rel="icon" href="/favicon.ico" />
<meta name='description' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaDescription : ''} />
<meta name='keywords' content={publishedArticle !== null && typeof publishedArticle !== typeof undefined ? publishedArticle.metaKeywords : ''} />
</Head>
<TopHeader mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<div className='flex flex-row h-full overflow-y-scroll'>
<UserSidebar slug={slug} mobileSidebarOpen={mobileSidebarOpen} setMobileSidebarOpen={setMobileSidebarOpen} />
<UserHelpContainer slug={slug} loading={loading} errors={errors} article={publishedArticle} />
</div>
</div>
</>
)
}
And in the TopHeader I have the following:
I am declaring TopHeader as follows (I've not included the whole thing as don't think its relevant)
const TopHeader = React.memo(function TopHeader(props: TopNavProps)
If the path is correct, you might not be exporting TopHeader as default?
export default TopHeader; // This will allow for generic import
And then to import:
import TopHeader from '../components/TopHeader'; // Can now use TopHeader
Edit: Included code blocks, cleaned answer and moved ramble to bottom...
I have never answered a question, so I planned on just commenting as this is more or less a question... But I must have more reputation to comment... Apologies..
I figured out my problem, thanks for the suggestions as it made me look at something and figure out the issue.
It was a rather dumb reason, where my SFTP client didn't fully upload and instead asked me a question which was hidden, so I didn't see it and therefore, only the top level directories uploaded, but deeper directories were missing some files hence the module not found error.
After getting this to work it it was an issue with CSS, this was to do with Tailwind purging CSS classes so had to add the following to tailwindcss.confnig.js
module.exports = {
purge:{
enabled: true,
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./components/*.{js,ts,jsx,tsx}',
'./JSFuncs/*.{js,ts,jsx,tsx}'
// Add more here
]
},

How to mock a imported function in vue component?

I'm testing my vue component, and I want to mock a function imported in component:
// backtop.vue
<template>
<transition name="ten-fade-in">
<div
v-if="_finishVisible"
class="ten-backtop"
:style="{
right: _offsetRight,
bottom: _offsetBottom
}"
#click="handleClick"
>
<!-- #slot 回到顶部内容 -->
<slot>
<ten-button
class="ten-backtop-button"
theme="default"
icon="backtop"
round
icon-only
/>
</slot>
</div>
</transition>
</template>
<script>
import throttle from 'lodash/throttle';
import TenButton from '../button';
import DomHelper from '#/components/scripts/utils/dom-helper';
const { scrollTo, getScroll } = DomHelper;
And all I want is to mock the "scrollTo" function.
// backtop.test.js
import Vue from "vue";
import { mount } from "#vue/test-utils";
jest.mock('#/components/scripts/utils/dom-helper', () => ({
scrollTo: jest.fn()
}));
import DomHelper from '#/components/scripts/utils/dom-helper';
const { scrollTo } = DomHelper;
import Backtop from '../backtop.vue';
But when I run the test, jest still uses the original real module in backtop.vue, the mock module only worked in backtop.test.js but didn't work in backtop.vue, any solution please?

Material-UI Theme : How to manage order or priority the .MuiXXX classes are applied?

[EDIT April 19th]
I have created a CODESANDBOX to show the problem, of course, that doesn't occur in sandbox.
The only difference between this code and mine is that I have duplicated the code of the Button component in the SANDBOX example, whereas in my App the Button component is imported from a library (that belongs to the same yarn workspace as the app). The library is built with webpack and babel, excluding React and Material-UI
externals: {
react: "react",
"react-dom": "react-dom",
"react-router": "react-router",
"react-router-dom": "react-router-dom",
"#material-ui/core": "#material-ui/core",
"#material-ui/icons": "#material-ui/icons",
"#material-ui/lab": "#material-ui/lab",
"#material-ui/styles": "#material-ui/styles",
formik: "formik",
},
Inspecting the components in the Browser shows the difference when styling, between sandbox and my app :
on both sides, the class are applied to the component the same way:
in sandbox
in my app
but on sandBox, the MuiButtonBase-root background-color is overridden by the MuiButton-root background-color
whereas it is the opposite in my app. The MuiButton-root backGroundColor seems to be overriden bu the MuiButtonBase-root background-color
However, if I create a component RecreatedButton in the App by just importing the Button component of my UI Library, and re-exported it without changing anything (just passing a specific props the component is requested), then the styling is applied correctly, as in the sandbox example.
this is kind of weird to me...
Why such a behavior ?
just importing and rexporting as is the component
import {
Button as LibraryButton,
EButtonTypes,
IButtonProps,
} from "#mylibrairy/reactcomponentscommon"; <---- importing the button
import React from "react";
const RecreatedButton: React.FC<IButtonProps> = (
props: IButtonProps
): JSX.Element => {
return (
<LibraryButton type={EButtonTypes.BUTTON}>
{props.children}
</LibraryButton>
);
};
export { RecreatedButton };
Using both in app.ts. One got the theme, the other not
import { ThemeProvider } from "#material-ui/core/styles";
import {
Button as LibraryButton,
EButtonTypes,
IButtonProps,
} from "#mylibrairy/reactcomponentscommon"
import React from "react";
import AppBar from "../../UIComponents/AppBar";
import { RecreatedButton } from "../../UIComponents/Button";
import { MUITheme } from "./../../Theming/defaultTheme";
export const MainApp: React.FC = (): JSX.Element => {
return (
<ThemeProvider theme={MUITheme}>
<>
<AppBar />
<LibraryButton type={EButtonTypes.BUTTON}> I'm the library component, directly used as is, and background color is NOT CORRECT ></LibraryButton>
<RecreatedButton>
I'm recreated button, just rexporting the library component, and the backgroundcolor is correct !?!?{" "}
</RecreatedButton>
</>
</ThemeProvider>
);
};
finally I found one solution (not sure that it fixes the root cause as I still do not understand where it comes from).
I Guess it may helps some people here that are facing a similar issue with global theming in Material-Ui.
It turned out that I had to change the way to build my react/material-Ui components library #mylibrairy/reactcomponentscommon.
1- Make sure that in the library, all imports where such as import { Button} from "#material-ui/core" and not for example import Button from "#material-ui/core/Button"
2- Remove the usage of file-loader plugin in the .babelrc to make sure it doesn't change the way to import material-ui components
3- Push #material-ui/core and #material-ui/icons as a dev and peer dependencies in the package.json of the library.
4- Rebuilt the library using webpack and babel to compile typescript tsx to js.
All issues of priority seems to disappear (have done a lot of tests and checked in the chrome dev tools). In the example above, the .MuiButton-root class is well applied after the .MuiButtonBase-root one, thus overriding as expected the backgroundColor.
Would admit that I'm a little bit confused why this fixed the issue...
Rgds
For me, i just had to import "makeStyles" and "createStyles" from "#material-ui/core" not from "#material-ui/core/styles". i just did this and it fixed the issue but took me a lot of time to figure this out.
so import them like this:
import { makeStyles, createStyles } from "#material-ui/core";
not like this:
import { makeStyles, createStyles } from "#material-ui/core/styles";
You may try overriding default globals for MuiButtonBase
const theme = createMuiTheme({
props: {
// Name of the component ⚛️
MuiButtonBase: {
// The default props to change
root:{
backgroundColor: 'red'
}
},
},
});
function DefaultProps() {
return (
<ThemeProvider theme={theme}>
<Button>Change default props</Button>
</ThemeProvider>
);
}
Working sandbox here - https://codesandbox.io/s/override-button-base-7qwd5

import Recharts.js library to jsx react file

I am looking to use Recharts as a graph system for my React app.
To install I have gone to the installation guide and entered the following command in the terminal
$ npm install recharts
My jsx file then looks like the code below:
import React from "react";
import ReactDOM from "react-dom";
import ReCharts from "recharts";
var App = React.createClass({
render: function() {
var data = [{ name: 'a', value: 12 }];
return (
<LineChart width={400} height={400} data={data}>
<Line type="monotone" dataKey="uv" stroke="#8884d8" />
</LineChart>
);
}
});
ReactDOM.render(<App/>, document.getElementById('app'));
It is not working as I am not importing recharges correctly. Can anyone advise and explain how this should be imported and any advice on how I soul know if I am exporting another library without any explicit guidance in its documentation.
You need import LineChart and Line components from Recharts, because this library does not have default exports Recharts index
import { LineChart, Line } from 'recharts';
Update
also you need change dataKey, from 'uv' to 'value' because in data you use value as key for chart values
Example

Resources