Jest - `Cannot create styled-component for component: undefined` - jestjs

I'm running into the following error when testing my application using jest:
FAIL
● Test suite failed to run
Cannot create styled-component for component: undefined.
30 |
31 |
> 32 | export const BackgroundVector = styled(Background)`
| ^
33 | position: fixed;
34 | left: 0;
35 | bottom: 0;
Background is an svg that I imported at the top of this file as follows:
import { ReactComponent as Background } from '../images/Background.svg';
I'm not quite sure how to get around this error. In my package.json, I have mapped SVG files to a fileMock.js which is just module.exports = 'test-file-stub';. Is there anything else I should do to resolve this?

You could try the following:
export const BackgroundVector = styled(props => <Background {...props}/>)`
//Your styles here
`
This solved my problem.

Related

polished function throws error only in test suite, not in actual app/browser

I have a button that utilises the lighten helper from polished (styled-componenents). I invoke it on hover like so:
FAB.styles.tsx
&:hover,
&:focus {
* {
cursor: pointer;
}
background: ${(props) => lighten(0.1, props.theme.primary)};
transition: background 0.25s;
}
No errors, works exactly as intended.
When I try to test that component at all, I get the following error:
Passed an incorrect argument to a color function, please pass a string representation of a color.
41 | }
42 |
> 43 | background: ${(props) => lighten(0.1, props.theme.primary)} !important;
Why is this only throwing an error here when no such errors are thrown in the browser?
The answer is to wrapp your tests in a ThemeProvider. You can do this with a custom render method, similar to the one they show in the testing-library docs on setup.
const Wrapper = ({ children }: any) => {
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};
export const customRender = (
ui: ReactElement,
options?: Omit<RenderOptions, "wrapper">
) => render(ui, { wrapper: Wrapper, ...options });
export * from "#testing-library/react";
it("renders something", () => {
customRender(<Component />);
const linkElement = screen.getByTitle(/Work with us/i);
expect(linkElement).toBeInTheDocument();
});
I found the answer thanks to the help of Brian Hough, one of the maintainers of polished/styled-components. You can see our thread here.

How to test a chart to see if it renders correctly

I need help, I wanted to test whether the graph is rendering to me by searching for the word that should appear after the graph is rendered, but it gets an error.
I am trying to write tests in JEST
Below is a function drawing a graph
export interface CharProps {
data:Array<any>,
labels:Array<any>
}
export const Graph: React.FC<CharProps> = ({labels,data}) => {
const [chartData, setChartData]= useState({})
const chart = ()=>{
setChartData({
labels:labels,
datasets:[
{
label: 'Annual revenue',
fill: false,
}
]
})
}
useEffect(()=>{
chart()
},[])
return (
<>
<div className={chartBackground}>
<Line data={chartData} options={{responsive:true}}/>
</div>
</>
);
}
And my test below
describe('<Graph /> ', () => {
it('should be redner', () => {
render(<Graph data={[65]} labels={['monday']} ></Graph>);
expect(screen.getByText('monday')).toBeTruthy;
});
})
And my bug
TypeError: Cannot set property '_options' of undefined
8 | describe('<Graph /> ', () => {
9 | it('should be redner', () => {
> 10 | render(<Graph data={[65]} labels={['monday']} ></Graph>);
| ^
11 | expect(screen.getByText('monday')).toBeTruthy;
12 | });
13 | })
I cannot understand it, please help.
With the limited context available I can only guess what the problem is. But it seems like Graph is unknown to jest. Please check if you have properly imported the Graph component in your test file or test helper.
More information on jest and react: https://jestjs.io/docs/en/tutorial-react

Error that history .push is not a function after clicking on signout in ReactJS

I am getting error that history .push is not a function after clicking on signout in ReactJS.
TypeError: history.push is not a function (anonymous function) C:/Users/Rina/Desktop/NodeApp/Ecommerce/ecommerce-front/src/core/Menu.js:39 36 | <span className="nav-link" 37 | style={{cursor: 'pointer', color: '#ffffff'}} 38 | onClick={() => signout(() => { > 39 | history.push('/'); | ^ 40 | }) 41 | } 42 | >```
In History API there is no something like history.push(). Probably you wanted to use history.pushState you can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/API/History_API?page=1
If you are using react hooks you can use like this
import { useHistory } from 'react-router';
function SignOut() {
const history = useHistory();
.....
history.push('/');
}

Git/node getting stuck on old .js -file version

I'm having a weird problem with git/node getting stuck to use an old version of .js-file.
Every once in a while after saving changes (so far only when the code has some errors in it, often after merge conflicts) the file gets somehow stuck in old version when building the app. Everything looks to be ok, VSCode changes the file and shows it just fine, but when trying to build the app, build process (both develop and production) uses the old fileversion with bugs in it.
This same thing is happening both on Win10 and MacOs.
I have found 2 ways to fix this (both are just workarounds)
Rename the file that is causing the problem
the old filename cannot be used even after it has been deleted and recreacted
Clone the branch with new name Re-clone the repository
Here are example files:
InfoComponents.js (this one had the error in it)
import React from 'react';
import Typography from '#material-ui/core/Typography';
import Battery from '#navigil/shared/src/components/SVGs/Battery';
import Box from '#navigil/shared/src/components/Box/Box';
import InfoBadge from './InfoBadge';
const batteryStatus = [80, 50, 15, 5];
const InfoComponents = ({ badges }) => (
<>
<Typography variant='h4'>Status / Warnings / Alarms</Typography>
<Box>
{badges.map((badge, index) => {
const { badgeProps, imageProps, imageComponent: Image } = badge;
return (
<InfoBadge key={index} {...badgeProps}>
<Image {...imageProps} />
</InfoBadge>
);
})}
</Box>
</>
);
export default InfoComponents;
Dashboard.js (this imports InfoComponents)
import React from 'react';
import Typography from '#material-ui/core/Typography';
import styled from 'styled-components';
import Battery from '#navigil/shared/src/components/SVGs/Battery';
import Box from '#navigil/shared/src/components/Box/Box';
import Button from '#navigil/shared/src/styledTheme/Components/Button';
import InfoComponents from './InfoComponents';
import { badges } from './testVariables';
const StyledButton = styled(Button)`
max-width: 100px;
`;
const NewWatchDashboard = () => (
<>
<InfoComponents badges={badges} />
</>
);
export default NewWatchDashboard;
And here is the parse error i'm receiving when build fails:
./src/InfoComponents/Dashboard.js
Line 7:28: Parse errors in imported module './InfoComponents': Line 14: Unexpected token
12 | <Box>
13 | {badges.map((badge, index) => ({
> 14 | <InfoBadge key={index} {...badgeProps}>
| ^
15 | <Image {...imageProps} />
16 | </InfoBadge>;
17 | }))} (14:9) import/namespace
Line 7:28: Parse errors in imported module './InfoComponents': Line 14: Unexpected token
12 | <Box>
13 | {badges.map((badge, index) => ({
> 14 | <InfoBadge key={index} {...badgeProps}>
| ^
15 | <Image {...imageProps} />
16 | </InfoBadge>;
17 | }))} (14:9) import/default
As you can see from above, the code in InfoComponents.js doesn't match the code in error message.
Creating a sandbox for this is kind of hard, because everything works just fine if I'm creating all of this from scratch. So it definetly looks to be a problem with Git.
Any ideas what could cause this and how to prevent it from happening?
Any ideas how to fix this easily when it happens?
-Jukka
Most probably the issue is with your local Git working tree.
Give a try with following:
#Copy the code from `InfoComponents.js` to some other file.
git rm --cached InfoComponents.js
#Commit the change
# add back the file with backed up content
# commit again
This might solve the issue.
Or
Try to clean your local git work tree:
git gc --prune=now
And check if your changes are reflected correctly.

My file is failing right at the very first line, import React from "react", with a TypeError: Object(...) is not a function

I'm working with the basic Gatsby starter site and it compiles just fine, but the browser just shows the error mentioned in the title as well as a couple warnings.
It's probably important to note that the error is gone when I completely remove the StaticQuery piece so the IndexPage component is just the opening and closing Layout tags. This gets rid of the error and the browser shows the header+footer of the Gatsby starter site.
I've made sure that my versions of react and react-dom are up to date in the package.json, I've reinstalled the packages via npm install, I've tried other versions of react, nothing is working.
The file that is failing (index.js):
import React from "react"
import { StaticQuery, GraphQL, Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<StaticQuery query={GraphQL`{
allWordpressPage {
edges {
node {
id
title
content
}
}
}
}`} render={props => (
<div> {props.allWordpressPage.edges.map(page => (
<div key={page.node.id}>
<h1>
{page.node.title}
</h1>
<div dangerouslySetInnerHTML={{__html: page.node.content}} />
</div>
))}
</div>
)}
/>
</Layout>
)
export default IndexPage
The error and warnings that show in browser:
TypeError: Object(...) is not a function
IndexPage
src/pages/index.js:1
> 1 | import React from "react"
2 | import { Link } from "gatsby"
3 |
4 | import Layout from "../components/layout"
View compiled
▶ 17 stack frames were collapsed.
JSONStore._this.handleMittEvent
/Users/kennansmith/Desktop/Temp_Task_Folder/gatsby-wp/.cache/json-store.js:1
> 1 | import React from "react"
2 |
3 | import PageRenderer from "./page-renderer"
4 | import normalizePagePath from "./normalize-page-path"
View compiled
▶ 2 stack frames were collapsed.
r.<anonymous>
/Users/kennansmith/Desktop/Temp_Task_Folder/gatsby-wp/.cache/socketIo.js:20
17 | // Try to initialize web socket if we didn't do it already
18 | try {
19 | // eslint-disable-next-line no-undef
> 20 | socket = io()
21 |
22 | const didDataChange = (msg, queryData) => {
23 | const id =
View compiled
▶ 24 stack frames were collapsed.
Maybe these imports are not the default ones?
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
check if they ere exported as default, otherwise you shuld use {} import
Ok, got it working again.
The issue was that I was using GraphQL instead of graphql. The case-sensitivity was throwing the whole thing off. Replacing both instances of GraphQL with graphql fixed the issue and now I am seeing my data rendered on the page as intended.

Resources