How to import amcharts 4 package in my file - javascript

I have a folder structure in my react project
node_modules
public
src
Inside my src I have a folder called test and inside the test i have a file test.js
I am writing some test cases inside my test file using react testing libarary.
here is my code
import React from 'react'
import { render, waitFor, screen,getAllByClassName,getByText, fireEvent, waitForElement, queryByAltText,getAllByRole, queryAllByText, queryAllByTestId, getAllByTestId, getByLabelText } from '#testing-library/react';
import { I18nextProvider } from 'react-i18next';
import DataService from '../DataServices/DataService.js';
import i18n from 'i18next';
//import POTable from '../views/Dashboard_HomePage/index';
import StockFairPage from '../views/StockFairValue/index';
//import draftToHtml from 'draftjs-to-html';
import '#testing-library/jest-dom';
import * as am4core from '../../node_modules/#amcharts/amcharts4/core';
import * as am4charts from '../../node_modules/#amcharts/amcharts4/charts';
jest.mock('axios');
jest.mock('../DataServices/DataService.js');
jest.mock('../i18n.js');
jest.mock('#amcharts/amcharts4', () => {
class Sprite {
constructor() {
this.path = '';
this.add = jest.fn();
this.stroke = jest.fn();
this.fill = jest.fn();
}
}
return {
core: {
Sprite,
},
};
});
when i am tuning the test case it is giving me an error
Cannot find module '#amcharts/amcharts4' from 'src/test/Dashboard.test.js'
18 |
19 |
> 20 | jest.mock('#amcharts/amcharts4', () => {
| ^
21 | class Sprite {
22 | constructor() {
23 | this.path = '';
I have also tried
import * as am4core from '#amcharts/amcharts4/core';
import * as am4charts from '#amcharts/amcharts4/charts';

Related

Cannot find module with absolute import Next+TS+Jest

I am using absolute imports and
testing a component with Context Provider in a NextJS project.
I have set this up according to jest setup
TEST:
import { render, screen } from 'test-util';
import { Sidebar } from '#/components/Sidebar/Sidebar';
test('if it has a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});
Here is my test-util.tsx in the root folder.
import React, { FC, ReactElement, ReactNode } from 'react';
import { render, RenderOptions } from '#testing-library/react';
import { AuthProvider } from 'store/auth';
const AllTheProviders: FC = ({ children }) => {
return <AuthProvider>{children}</AuthProvider>;
};
const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) =>
render(ui, { wrapper: AllTheProviders, ...options });
export * from '#testing-library/react';
export { customRender as render };
This is my jest.config.js in the root folder
// #ts-nocheck
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
// Handle module aliases (this will be automatically configured for you soon)
'^#/components/(.*)$': '<rootDir>/components/$1',
'^#/pages/(.*)$': '<rootDir>/pages/$1',
'^#/firebase/(.*)$': '<rootDir>/firebase/$1',
'^#/store/(.*)$': '<rootDir>/store/$1',
},
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Here is jest.setup.js in the root folder
import '#testing-library/jest-dom/extend-expect';
I get this error:
FAIL components/Sidebar/__test__/Sidebar.test.tsx
● Test suite failed to run
Cannot find module 'test-util' from 'components/Sidebar/__test__/Sidebar.test.tsx'
1 | import { Sidebar } from '#/components/Sidebar/Sidebar';
> 2 | import { render } from 'test-util';
| ^
3 |
Here is tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/pages/*": ["./pages/*"],
"#/components/*": ["./components/*"],
"#/features/*": ["./features/*"],
"#/firebase/*": ["./firebase/*"],
"#/store/*": ["./store/*"]
}
}
}
How to solve this issue? I want to use
import { render, screen } from 'test-util';
What works:
import { render, screen } from '../../../test-util';
import { Sidebar } from '#/components/Sidebar/Sidebar';
test('if it has a brand image', () => {
render(<Sidebar />);
const brandLogo = screen.getByAltText('logo');
expect(brandLogo).toBeInTheDocument();
});
I have a similar config, but it works for me.
Try to add moduleDirectories: ["node_modules", "<rootDir>/"]
inside your customJestConfig object.

How to import modules during tests using jest?

I'm using React, Enzyme and Jest. This is my connect component which only renders a button
import { connect } from 'react-redux';
import { withStyles } from '#material-ui/core/styles';
import PlaidLinkButton from 'react-plaid-link-button';
const plaidEnv = process.env.REACT_APP_PLAID_ENV
export class ConnectStep extends Component {
handleOnSuccessBroker = async (token, metadata) => {
//unimportant
};
render() {
const { classes } = this.props;
return (
<PlaidLinkButton
buttonProps={{
className: classes.connectButton,
id: 'button',
}}
plaidLinkProps={{
clientName: '###',
key: '###',
env: plaidEnv,
product: ['transactions'],
onSuccess: this.handleOnSuccessBroker,
token: ''
}}
>
{this.props.plaid.accounts.length > 0 ? 'CONNECTED' : 'Start'}
</PlaidLinkButton>
);
}
}
As you can see Im importing PlaidLinkButton but jest throws this error:
###/node_modules/react-plaid-link-button/dist/react-plaid-link-button/react-plaid-link-button.js:19
import PropTypes from 'prop-types';
^^^^^^^^^
SyntaxError: Unexpected identifier
4 |
5 | import { setPlaid } from '../../../actions/actions';
> 6 | import PlaidLinkButton from 'react-plaid-link-button';
What am I missing? I made successful test suites for other components that also import modules. But this one in particular is giving me problems.
import PropTypes from 'prop-types';
^^^^^^^^^
SyntaxError: Unexpected identifier
This is likely an issue related to your Jest/Babel config because the modules aren't getting compiled correctly. You'd need to remove anywhere you set the Babel option modules to false.
Related: https://github.com/facebook/react/issues/14399

Error testing a function component in react testing

I'm learning about react testing but I have some issues.
I'm trying to test a functional component in react
import React, {useState, useEffect, useContext} from 'react';
import DayPicker from 'react-day-picker/DayPickerInput';
import MomentLocaleUtils, {
formatDate,
parseDate,
} from 'react-day-picker/moment';
import 'react-day-picker/lib/style.css';
import 'moment/locale/pt-br';
import Swal from 'sweetalert2';
import $ from 'jquery';
import api from 'config/api';
import {InvestmentsContext} from 'context/InvestmentsContext';
export default props => {
const [investments, setInvestments] = useContext(InvestmentsContext);
const [investment, setInvestment] = useState({
type: 'RENDA_FIXA',
value: '',
date: new Date(),
});
...
return (
<>
<form onSubmit={e => save(e, investment)} className="investment-form">
...
</form>
</>
);
};
But i'm getting this error when I try to test it with Jest and Enzyme
TypeError: Invalid attempt to destructure non-iterable instance
13 | import {InvestmentsContext} from 'context/InvestmentsContext';
14 |
> 15 | export default props => {
| ^
My Spec:
import React from 'react';
import {configure, mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Form from 'components/investment/Form';
configure ({adapter: new Adapter ()});
let wrapper;
describe ('<Form />', () => {
beforeEach (() => {
wrapper = mount (<Form onCountChange={'a'} />);
});
it ('button should be disabled if investment value is empty', () => {
expect (wrapper.find ('.btn-action')).toHaveAttribute ('disabled');
});
});
Why am I getting this? Due to my component be a function?

Asset.fromModule is not a function. (In 'Asset.fromModule(image)', 'Asset.fromModule' is undefined)

After updating to Expo sdk 34, I am getting this error:
TypeError: Asset.fromModule is not a function. (In 'Asset.fromModule(image)', 'Asset.fromModule' is undefined).
I have ran the cod-mod which Expo recommends using this command: npx expo-codemod sdk33-imports src when updating to new versions, and I've also tried changing import * as Asset from 'expo-asset'; to import { Asset } from 'expo-asset', but neither of these changes have fixed this warning.
This is my App.js
import React from 'react';
import { Dimensions, Alert } from 'react-native';
import {Root} from 'native-base';
import {createRootNavigator} from './router';
import {configureFontAwesomePro} from "react-native-fontawesome-pro";
import Geocoder from 'react-native-geocoding';
import { AppLoading } from 'expo';
import * as Asset from 'expo-asset';
import * as Font from 'expo-font';
import Api from './services/api';
import Moment from 'moment';
import Config from './config/config';
import './i18n';
import store from './store/store';
import i18n from 'i18n-js';
configureFontAwesomePro();
const RootNav = createRootNavigator();
function cacheImages(images) {
return images.map(image => {
if (typeof image === 'string') {
return Image.prefetch(image);
} else {
return Asset.fromModule(image).downloadAsync();
}
});
}
function cacheFonts(fonts) {
return fonts.map(font => Font.loadAsync(font));
}
export default class App extends React.Component {
constructor() {
super();
this.state = {
isReady: false
};
}
async _loadAssetsAsync() {
const imageAssets = cacheImages([
require('./assets/images/splash.png'),
require('./assets/images/splash-logo.png'),
require('./assets/images/hotdrink.png'),
require('./assets/images/insta.png'),
require('./assets/images/twitter.png'),
require('./assets/images/facebook.png'),
require('./assets/images/yelp.png'),
]);
store.updatePrefix(Expo.Linking.makeUrl('/'));
const fontAssets = cacheFonts(
[{
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
Ionicons: require("#expo/vector-icons")
}]
);
await Promise.all([...imageAssets, ...fontAssets]);
}
render() {
if (!this.state.isReady) {
return (<AppLoading
startAsync={this._loadAssetsAsync}
onFinish={() => this.setState({isReady: true})}
onError={(error) => console.log('app js: ', error)}
/>)
}
return (
<Root>
<RootNav uriPrefix={store.prefix} />
</Root>
)
}
}
Geocoder.init(Config.google_maps_key);
Edit:
After making the changes suggested below:
- changing the import of asset from import * as Asset from 'expo-asset'; to import { Asset } from 'expo-asset';
- I am now getting this error, which is slightly different than the one
I originally wrote about
- TypeError: asset.downloadAsync is not a function. (In 'asset.downloadAsync()', 'asset.downloadAsync' is undefined).
Seems like this should just be import { Asset } from "expo-asset"; instead of import * as Asset from 'expo-asset';.
I figured this out since that import statement looked odd, so I copied your App.js into a fresh create-react-native-app install, added a few of the dependencies and commented out the bits that seemed unrelated or references to files that aren't posted here. I got the TypeError: Asset.fromModule is not a function. (In 'Asset.fromModule(image)', 'Asset.fromModule' is undefined) warning, changed the import line, and the app loaded (it didn't do much, but with so much commented out that was expected).
The import statement is pretty easy to accidentally get wrong without actually generating an errors on the import line, may be worth refreshing on how as works when using it, see the docs on MDN
Run this in your root folder:
expo install expo-asset
And then run
expo start -c
just to be sure.

module export - Getting property 'default' of undefined in React Native

Facing problem with importing and exporting files. This was working with react-native 0.51.0
But not in react-native: 0.56
"babel-eslint": "7.2.3",
"babel-plugin-transform-remove-console": "6.9.0",
"babel-preset-react-native": "^5",
Is it a problem with module.exports and export default or with babel version?
Getting error saying that
Cannot read property 'default' of undefined
Object.get [as API]
repolib/index.js
import * as components from './components';
import * as utils from './utils';
var Utils = {
Logger: utils.Logger,
Toast: utils.Toast
}
var Components = {
Button: components.Button
}
module.exports = {
Utils,
Components,
}
Utils/Toast.js
var Toast = require('../repolib').Utils.Toast;
export default {
...(Toast)
}
API/loginAPI.js
import Toast from '../Utils/Toast';
export default {
login: () => {...}
}
API/index.js
import loginAPI from './loginAPI';
export default {
loginAPI
}
common/index.js
export { default as API } from '../API';

Categories