I am trying to run unit tests in a React project generated using react-scripts, in which I added ReScript support.
When I run the tests, however, I encountered an error in the transpiled javascript code.
Details of the error:
/Users/massimilianodacunzo/Projects/Elixir/test-project/apps/phoenix_react_web/assets/node_modules/bs-platform/lib/es6/array.js:3
import * as Curry from "./curry.js";
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
2 |
> 3 | import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
| ^
4 | import * as React from "react";
5 |
6 | function TestComponent(Props) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/components/users/TestComponent.bs.js:3:1)
The components I am trying to test:
App.res
%%raw(`
import logo from './logo.svg';
import './App.css';
`)
#react.component
let make = () => {
<div className="App">
<TestComponent elements={["1", "2", "3"]} />
</div>
}
TempComponent.res
#react.component
let make = (
~elements: array<string>
) => {
<ul>
{
React.array(
elements
|> Array.map(e =>
<li key={e}>{React.string(e)}</li>)
)
}
</ul>
}
The generated TestComponent.bs.js
import * as $$Array from "../../../node_modules/bs-platform/lib/es6/array.js";
import * as React from "react";
function TestComponent(Props) {
var elements = Props.elements;
return React.createElement("ul", undefined, $$Array.map((function (e) {
return React.createElement("li", {
key: e
}, e);
}), elements));
}
var make = TestComponent;
export {
make ,
}
/* react Not a pure module */
Is there any additional configuration I can add to the react-scripts test script?
Following the comment of glennsl, I followed the git issue, discovering that the configuration in my bsconfig.json file specified the package-specs module as es6. The test error didn't appear if I change the configuration to commonjs.
{
...
"package-specs": {
"module": "commonjs",
"in-source": true
}
...
}
Again, thanks to glennsl for pointing me in the right direction.
Related
I have the following issue when I tried to test a react components that implement the react-leaflet library
C:\digital-booking-ui\node_modules\react-leaflet\lib\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { useMap, useMapEvent, useMapEvents } from './hooks.js';
^^^^^^
SyntaxError: Unexpected token 'export'
1 | import React from "react";
2 | import { makeStyles } from "#material-ui/core";
> 3 | import { MapContainer, TileLayer, Marker, Popup, useMap } from "react-leaflet";
| ^
4 |
5 | const Map = () => {
6 | const classes = useStyles();
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/accomodation/Map.js:3:1)
I search the problem on the internet and the recommendations I found don't work for me.
This error happen when I tried to render any component that has a relation with that library, for example, App.test.js
import { render, screen, prettyDOM } from '#testing-library/react';
import '#testing-library/jest-dom/extend-expect'
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import { ThemeProvider } from '#material-ui/core';
import theme from "./theme";
let component = null;
beforeEach(() => {
component = render(
<BrowserRouter>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</BrowserRouter>
);
}
);
test('render App', () => {
expect(component).toBeTruthy();
});
How could I fix this? It seems a problem of Jest not recognizing the export of the components
In your package.json add these lines
"jest": {
"moduleNameMapper": {
"react-leaflet": "<rootDir>/mocks/reactLeafletMock.js"
}
}
Then in a "mocks" folder (or whatever you want) add a reactLeafletMock.js module that return an empty object
module.exports = {}
It should be ok (it worked for me)
You could eventually add "react-leaflet" hooks within the object to avoid other errors from Jest
module.exports = {
useMapEvents: () => {}
}
I am trying to deploy a react JS app and am stuck at npm run build. My command line is throwing this error when I attempt to compile my react js (typescript) project with npm run build command:
Type error: Argument of type 'firebase.default.auth.Auth' is not assignable to parameter of type 'import("/Users/jaxfloyd/Documents/Programming/The_Sportsbook/get-rich-or-die-trying/growth/next-firebase-stripe/node_modules/#firebase/auth/dist/auth-public").Auth'
The CLI points to my index.tsx file as the problem:
7 |
8 | export default function Home() {
9 | const [user, userLoading] = useAuthState(firebase.auth());
| ^
10 | console.log("User is:", user);
11 |
12 | return (
This is my full index.tsx file:
import React from "react";
import Login from "../components/Login";
import styles from "../styles/Home.module.css";
import firebase from "../firebase/firebaseClient";
import { useAuthState } from "react-firebase-hooks/auth";
import { createCheckoutSession } from "../stripe/createCheckoutSession";
export default function Home() {
const [user, userLoading] = useAuthState(firebase.auth());
console.log("User is:", user);
return (
<div className={styles.container}>
{!user && userLoading && <h1>Loading...</h1>}
{!user && !userLoading && <Login />}
{user && !userLoading && (
<div>
<h1>Hello, {user.displayName}</h1>
<button onClick={() => createCheckoutSession(user.uid)}>
Upgrade to premium!
</button>
</div>
)}
</div>
);
}
Nothing online has an alternate import statement I can use for useAuthState. Any help would be much appreciated.
There are two versions of Firebase, you are using them together instead of just one. Use Firebase version 8 or 9 not both of them. If library "react-firebase-hooks/auth" is using functional approach, use Firebase version 9 to get Auth. You need to use function import { getAuth } from 'firebase/auth'. Same i dont know how you initialize app in version 9 you can do it using function import { initializeApp } from 'firebase/app'.
My tests were working fine until recently, and they all still run & pass just fine except the top-level App component smoke test.
Test code:
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { render, waitFor } from '#testing-library/react';
import { ToastProvider } from 'react-toast-notifications'
import App from './App';
it('renders without crashing', async () => {
const { getByText } = render(
<MemoryRouter>
<ToastProvider>
<App />
</ToastProvider>
</MemoryRouter>
);
await waitFor(() => {
expect(getByText("You'll need to sign in to use this feature.")).toBeInTheDocument();
});
});
The Error:
Test suite failed to run
SyntaxError: /Users/druserkes/Desktop/zephyrx/zephyrx-dr-dashboard/node_modules/react-toast-notifications/dist/ToastContainer.js: pragma and pragmaFrag cannot be set when runtime is automatic.
> 1 | 'use strict';
| ^
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
at File.buildCodeFrameError (node_modules/react-scripts/node_modules/#babel/core/lib/transformation/file/file.js:250:12)
at NodePath.buildCodeFrameError (node_modules/#babel/traverse/lib/path/index.js:138:21)
at PluginPass.enter (node_modules/babel-preset-react-app/node_modules/#babel/plugin-transform-react-jsx/lib/create-plugin.js:163:28)
at newFn (node_modules/#babel/traverse/lib/visitors.js:175:21)
at NodePath._call (node_modules/#babel/traverse/lib/path/context.js:55:20)
at NodePath.call (node_modules/#babel/traverse/lib/path/context.js:42:17)
at NodePath.visit (node_modules/#babel/traverse/lib/path/context.js:92:31)
at TraversalContext.visitQueue (node_modules/#babel/traverse/lib/context.js:116:16)
at TraversalContext.visitSingle (node_modules/#babel/traverse/lib/context.js:85:19)
at TraversalContext.visit (node_modules/#babel/traverse/lib/context.js:144:19)
Commenting out the 'use strict' line in file in node_modules doesn't change anything.
Any help would be greatly appreciated.
I created some basic tests and followed the getting started guide on Jests website, but toHaveAttribute is not a function apparently
import React from "react";
import { fireEvent, render } from "#testing-library/react";
import userEvent from "#testing-library/user-event";
import { App } from "../App";
test("allows users to add items to their list", () => {
const { getByText, getByLabelText, getByTestId } = render(<App />);
const input = getByLabelText("What needs to be done?");
userEvent.type(getByTestId("email"), "Hello World!")
expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
})
TypeError: expect(...).toHaveAttribute is not a function
10 | const input = getByLabelText("What needs to be done?");
11 | userEvent.type(getByTestId("email"), "Hello World!")
> 12 | expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
| ^
13 | })
I followed the tutorial exactly so im unsure why this is happening.
The method toHaveAttribute is part of jest-dom that enables to test DOM elements. You need to verify if you have setup it properly at your project.
Install the module:
npm install --save-dev #testing-library/jest-dom
After that you can include at your jest setup file like recommended:
// In your own jest-setup.js (or any other name)
import '#testing-library/jest-dom'
// In jest.config.js add (if you haven't already)
setupFilesAfterEnv: ['<rootDir>/jest-setup.js']
I faced the same issue but easily solved it using playwright native getter - .getAttribute('someAttribute');
For example you can write something like that:
const locator = await page.locator('[name="SomeLocator"]').getAttribute('content');
I have an alternative where you use getAttribute
import { render, screen } from '#testing-library/svelte';
it('should render avatar of user', async () => {
const image = screen.getByAltText(`${MOCK_NAVBAR.username} avatar`);
expect(image.getAttribute('src')).toBe(MOCK_NAVBAR.userAvatar);
});
I added to my gatsby's webpack config directory-named-webpack-plugin which makes it possible to import files that have the same name as its parent direcory. For example I can use path 'components/Link' instead of 'components/Link/Link':
const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
resolve: {
plugins: [new DirectoryNamedWebpackPlugin()],
},
});
};
But unfortunately when I run my test using jest I get an error like that (I also use absolute imports):
FAIL src/components/atoms/Link/Link.test.js
● Test suite failed to run
Cannot find module 'components/atoms/Icon' from 'src/components/atoms/Link/Link.js'
Require stack:
src/components/atoms/Link/Link.js
src/components/atoms/Link/Link.test.js
3 | import { useAnimation } from 'framer-motion';
4 | import PropTypes from 'prop-types';
> 5 | import Icon from 'components/atoms/Icon';
| ^
6 | import arrow from 'assets/svgs/icon_arrow.svg';
7 | import S from './Link.styles';
8 | import animations from './Link.animations';
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:307:11)
at Object.<anonymous> (src/components/atoms/Link/Link.js:5:1)
Here is my folder structure:
Is there any solution to this? I'm pretty new in the jest configuration.
Use index.js in each folders like this and forget DirectoryNamedWebpackPlugin at all
import Link from './Link';
export default Link;