Hi I am creating an SPFX weather webpart and i am getting this error:
there are no errors when i run gulp build. i am not sure how to debug my issue. this is the snippet of the proptypes.shape() where i am getting my issue:
import * as React from 'react';
import PropTypes from 'prop-types';
export const Day: React.SFC<any> = props => {
const date = props.day.dt;
const icon = getIcon(props.day.weather[0].id);
const animate = true;
const iconSize = 64;
const iconColor = 'black';
return (
<div className={appClasses.dayContainer} onClick={props.onClick} role="link">
<h2 className={appClasses.date}>{(new Date(date * 1000)).toDateString()} - {(new Date(date * 1000)).toLocaleTimeString()}</h2>
<ReactAnimatedWeather
icon={icon}
color={iconColor}
size={iconSize}
animate={animate}
/>
</div>
);
};
Day.defaultProps = {
onClick: () => {},
};
Day.propTypes = {
day: PropTypes.shape({
dt: PropTypes.number.isRequired,
weather: PropTypes.array.isRequired,
}).isRequired,
onClick: PropTypes.func,
};
I'd like to note that i created the webpart first using react and it is working perfectly, but when i created an SPFX app, and transferred my existing codes into it. I had encountered these errors.
This is my package.json
{
"name": "spfx-weather-2",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=0.10.0"
},
"dependencies": {
"#microsoft/sp-core-library": "~1.1.0",
"#microsoft/sp-webpart-base": "~1.1.1",
"#types/react": "0.14.46",
"#types/react-addons-shallow-compare": "0.14.17",
"#types/react-addons-test-utils": "0.14.15",
"#types/react-addons-update": "0.14.14",
"#types/react-dom": "0.14.18",
"#types/webpack-env": ">=1.12.1 <1.14.0",
"prop-types": "^15.6.1",
"react": "15.4.2",
"react-animated-weather": "^1.0.3",
"react-dom": "15.4.2",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"#microsoft/sp-build-web": "~1.1.0",
"#microsoft/sp-module-interfaces": "~1.1.0",
"#microsoft/sp-webpart-workbench": "~1.1.0",
"gulp": "~3.9.1",
"#types/chai": ">=3.4.34 <3.6.0",
"#types/mocha": ">=2.2.33 <2.6.0"
},
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
}
}
Check my answer here [SPLoaderError.loadComponentError]: ***Failed to load component
You very likely have the same issue. If you were to post your github link for me to clone I could confirm for you.
TL;DR
You likely have a circular reference between your factories. You need to move any code that is required from your top level factory to the bottom of said factory.
Let me know if you don't quite understand after reading my other answer.
Related
I am creating a project on a React Native application, and I am using Expo. I would like to add ads, so I'm using Google Ad Mob. So I created my account on the site. I have a problem and it's been a long time that I can't solve it.
I have this error:
` ERROR Invariant Violation: Your JavaScript code tried to access a native module that doesn't exist.
If you're trying to use a module that is not supported in Expo Go, you need to create a development build of your app. See https://docs.expo.dev/development/introduction/ for more info.
ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.`
here is my package.json:
{
"name": "front",
"version": "1.0.0",
"scripts": {
"start": "expo start --dev-client",
"android": "expo run:android",
"ios": "expo run:ios",
"web": "expo start --web"
},
"dependencies": {
"#expo/vector-icons": "^13.0.0",
"#react-navigation/drawer": "^6.5.7",
"#react-navigation/native": "^6.1.2",
"#react-navigation/native-stack": "^6.9.8",
"axios": "^1.2.2",
"expo": "~47.0.12",
"expo-build-properties": "~0.4.1",
"expo-dev-client": "~2.0.1",
"expo-secure-store": "~12.0.0",
"expo-splash-screen": "~0.17.5",
"expo-status-bar": "^1.4.2",
"react": "18.1.0",
"react-native": "0.70.5",
"react-native-animated-loader": "^1.0.0",
"react-native-gesture-handler": "~2.8.0",
"react-native-google-mobile-ads": "^9.1.1",
"react-native-infinite-scroll-view": "^0.4.5",
"react-native-keyboard-aware-scroll-view": "^0.9.5",
"react-native-reanimated": "~2.12.0",
"react-native-safe-area-context": "4.4.1",
"react-native-screens": "~3.18.0",
"react-native-toast-message": "^2.1.5",
"react-navigation": "^4.4.4",
"react-router": "^6.6.2"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"react-native-secure-store": "^1.0.3"
},
"private": true
}
and here is the file in which I use ad mob:
import React, { useState } from "react";
import { View, Text, Button, Alert, TouchableOpacity } from 'react-native';
import { SafeAreaView } from "react-native-safe-area-context";
import { RewardedAd, RewardedAdEventType, TestIds } from 'react-native-google-mobile-ads';
const adUnitId = __DEV__ ? TestIds.REWARDED : 'ca-app-pub-blablabla';
const rewarded = RewardedAd.createForAdRequest(adUnitId, {
requestNonPersonalizedAdsOnly: true,
keywords: ['fashion', 'clothing'],
});
const Video = () => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const unsubscribeLoaded = rewarded.addAdEventListener(RewardedAdEventType.LOADED, () => {
setLoaded(true);
});
const unsubscribeEarned = rewarded.addAdEventListener(
RewardedAdEventType.EARNED_REWARD,
reward => {
console.log('User earned reward of ', reward);
},
);
// Start loading the rewarded ad straight away
rewarded.load();
// Unsubscribe from events on unmount
return () => {
unsubscribeLoaded();
unsubscribeEarned();
};
}, []);
if (!loaded) {
return null;
}
return (
<View style={{alignItems: "center", justifyContent: "center"}}>
<TouchableOpacity style={{borderColor: "blue", padding: 30}}>
<Text onPress={() => rewarded.show()}>Watch Rewarded Ad</Text>
</TouchableOpacity>
</View>
);
};
export default Video;
I re-installed the nodes modules, I added this to my app.json file:
"plugins": [
[
"expo-build-properties",
{
"android": {
"compileSdkVersion": 31,
"targetSdkVersion": 31,
"buildToolsVersion": "31.0.0"
},
"ios": {
"deploymentTarget": "13.0"
}
}
]
]
},
"react-native-google-mobile-ads": {
"android_app_id": "ca-app-pub-2973173763441523~2444055698",
"ios_app_id": "ca-app-pub-2973173763441523~5693853805"
}
I followed the installation guide, so if anyone can help me to use Ad mob I would love it, thanks!
The code was working fine in react-redux v5 but when I upgraded to v7 I obtained the following runtime error when navigating to the page with the CartContainer:
react-dom.development.js:11102 Uncaught Error: Could not find "store" in the context of
"Connect(CartContainer)". Either wrap the root component in a <Provider>, or pass a custom
React context provider to <Provider> and the corresponding React context consumer
to Connect(CartContainer) in connect options.
Now I do wrap the root-level component in a Provider, in the typical gatsby way,
Here is the ReduxWrapper.js file:
import React from 'react';
import { Provider } from 'react-redux';
import { getAllProducts } from './src/actions'
import { createStore, applyMiddleware } from 'redux'
import { createLogger } from 'redux-logger'
import thunk from 'redux-thunk'
import rootReducer from './src/reducers';
const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger());
}
const store = createStore(rootReducer,applyMiddleware(...middleware))
store.dispatch(getAllProducts())
export default ({ element }) => (
<Provider store={store}>{element}</Provider>
);
The store instance should run downstream into any container that has connect() called on it.
additionally both gatsby-Browser.js and gatsby-ssr.js have the following:
export { default as wrapRootElement } from './ReduxWrapper';
the connected component in question, CartContainer.js is given below:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { checkout } from '../actions'
import { getTotal, getCartProducts } from '../reducers'
import Cart from '../components/checkout/Cart'
const CartContainer = ({ products, total, checkout }) => (
<Cart
products={products}
total={total}
onCheckoutClicked={() => checkout(products)} />
)
CartContainer.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
quantity: PropTypes.number.isRequired
})).isRequired,
total: PropTypes.string,
checkout: PropTypes.func.isRequired
}
const mapStateToProps = (state) => ({
products: getCartProducts(state),
total: getTotal(state)
})
export default connect(
mapStateToProps,
{ checkout }
)(CartContainer)
I am expecting CartContainer to have access to the store, and I suspect the problem lies with the fact I upgraded react-redux from v5 to v7, Since everything was working fine until that moment.
My dependencies:
{
"name": "gatsby-starter-default",
"private": true,
"description": "A simple starter to get up and developing quickly with Gatsby",
"version": "1.0.0",
"author": "David W",
"dependencies": {
"#fortawesome/fontawesome": "^1.1.8",
"#fortawesome/fontawesome-free": "^5.12.1",
"#fortawesome/fontawesome-svg-core": "^1.2.27",
"#fortawesome/free-brands-svg-icons": "^5.12.1",
"#fortawesome/free-solid-svg-icons": "^5.12.1",
"#fortawesome/react-fontawesome": "^0.1.9",
"#reach/router": "^1.3.3",
"bootstrap": "^4.4.1",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"gatsby": "^2.19.45",
"gatsby-background-image": "^0.10.2",
"gatsby-image": "^2.2.43",
"gatsby-plugin-env-variables": "^1.0.1",
"gatsby-plugin-manifest": "^2.2.39",
"gatsby-plugin-offline": "^3.0.32",
"gatsby-plugin-react-helmet": "^3.1.23",
"gatsby-plugin-sass": "^2.1.29",
"gatsby-plugin-sharp": "^2.4.3",
"gatsby-source-filesystem": "^2.1.46",
"gatsby-transformer-sharp": "^2.3.13",
"google-map-react": "^1.1.6",
"jquery": "^3.4.1",
"node-sass": "^4.13.1",
"nodemailer": "^6.4.3",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-bootstrap": "^1.0.0-beta.17",
"react-dom": "^16.13.1",
"react-fontawesome": "^1.7.1",
"react-helmet": "^5.2.1",
"react-map-gl": "^5.2.3",
"react-redux": "^7.2.0",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"typescript": "^3.8.3"
},
"devDependencies": {
"prettier": "^1.19.1"
},
"keywords": [
"gatsby"
],
"license": "MIT",
"scripts": {
"build": "gatsby build",
"develop": "gatsby develop",
"format": "prettier --write \"**/*.{js,jsx,json,md}\"",
"heroku-postbuild": "gatsby build",
"start": "gatsby serve",
"serve": "gatsby serve",
"clean": "gatsby clean",
"test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/gatsbyjs/gatsby-starter-default.git"
},
"bugs": {
"url": "https://github.com/gatsbyjs/gatsby/issues"
},
"homepage": "https://github.com/gatsbyjs/gatsby-starter-default#readme",
"main": "gatsby-browser.js"
}
How can I write a jest unit test for a react native component which contains a NavigationEvents subcomponent.
I've tried the solutions offered in questions here and here without success.
The error I am getting is
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9215
The above error occurred in the <Context.Consumer> component:
in withNavigation(NavigationEvents) (created by MyComponent)
in View (created by View)
in View (created by MyComponent)
in MyComponent
Consider adding an error boundary to your tree to customize error handling behavior.
● MyComponent test › renders
Invariant Violation: withNavigation can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context.
Below is a minimal example that causes the error.
import 'react-native';
import { View } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import React from 'react';
import renderer from 'react-test-renderer';
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<NavigationEvents/>
</View>
);}
}
describe('MyComponent test', () => {
it('renders', () => {
jest.mock('react-navigation', () =>({
NavigationEvents: 'mockNavigationEvents',
withNavigation: component => component
}));
const navigation = { navigate: jest.fn() };
renderer.create(<MyComponent navigation={navigation}/>);
});
});
Edit
As requested in comments added package.json below:
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"eject": "expo eject",
"test": "node ./node_modules/jest/bin/jest.js --watchAll"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"#expo/samples": "2.1.1",
"#expo/vector-icons": "^10.0.0",
"expo": "^35.0.0",
"expo-camera": "~7.0.0",
"expo-sqlite": "^7.0.0",
"moment": "^2.24.0",
"react": "16.8.3",
"react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",
"react-native-action-button": "^2.8.5",
"react-native-calendar-picker": "^6.0.0",
"react-native-dialog": "^5.6.0",
"react-native-dotenv": "^0.2.0",
"react-native-dynamic-search-bar": "^0.1.11",
"react-native-elements": "^1.1.0",
"react-native-gesture-handler": "~1.3.0",
"react-native-keyboard-aware-scroll-view": "^0.9.1",
"react-native-modal-datetime-picker": "^7.4.0",
"react-native-paper": "^2.15.2",
"react-native-progress-circle": "^2.1.0",
"react-native-search-bar": "^3.4.2",
"react-native-vector-icons": "^6.4.2",
"react-navigation": "^3.0.9",
"expo-constants": "~7.0.0",
"expo-file-system": "~7.0.0"
},
"devDependencies": {
"babel-preset-expo": "^7.0.0",
"jest-expo": "^35.0.0"
},
"private": true
}
expo-cli version
$ expo-cli -V
3.13.1
The problem is that jest.mock has to be outside of describe and it functions. You don't need to manually mock navigation object since you're mocking the withNavigation HOC function:
// Setup mocks outside describe and it functions
jest.mock('react-navigation', () =>({
NavigationEvents: 'mockNavigationEvents',
withNavigation: component => component
}));
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View>
<NavigationEvents/>
</View>
);
}
}
describe('MyComponent test', () => {
it('renders', () => {
renderer.create(<MyComponent/>);
});
});
And the renders test passes:
I suggest you have all those mocks inside a file and set setupFilesAfterEnv in package.json:
package.json > jest:
"jest": {
"preset": "jest-expo"
"setupFilesAfterEnv": ["./path/to/jestInit.js"]
},
jestInit.js:
jest.mock('react-navigation', () =>({
NavigationEvents: 'mockNavigationEvents',
withNavigation: component => component
}));
This way, you'll have those mocks for every Jest test file without having to include the mocks inside each test file.
My app uses CRNA and Expo, and my issue is that the Font.loadAsync() asynchronous function can't locate a .otf font file in the assets/fonts/ folder in my project directory. I am absolutely sure that the directory and file names are correct. I receive this error.
link to image of my error screen
Here is my code:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Font, AppLoading } from 'expo'
import Root from './js/Root';
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
fontLoaded: false
}
}
async componentDidMount() {
await Font.loadAsync({
"Light": require('./assets/fonts/SemplicitaPro-Light.otf')
})
this.setState({ fontLoaded: true })
}
render() {
if (!this.state.fontLoaded) {
return <AppLoading />
}
return <Root />;
}
}
Here is my package.json:
{
"name": "Zumer",
"version": "0.1.0",
"private": true,
"devDependencies": {
"flow-bin": "^0.40.0",
"jest-expo": "^0.4.0",
"react-native-scripts": "0.0.28",
"react-test-renderer": "16.0.0-alpha.6"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "node node_modules/jest/bin/jest.js --watch",
"flow": "flow"
},
"packagerOpts": {
"assetExts": ["ttf", "otf"]
},
"jest": {
"preset": "jest-expo",
"tranformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation)"
]
},
"dependencies": {
"#expo/vector-icons": "^4.0.0",
"expo": "^16.0.0",
"native-base": "^2.1.2",
"react": "16.0.0-alpha.6",
"react-native": "^0.43.4",
"react-native-elements": "^0.11.1",
"react-navigation": "^1.0.0-beta.8",
"react-redux": "^5.0.4",
"redux": "^3.6.0",
"redux-observable": "^0.14.1",
"redux-persist": "^4.6.0",
"rxjs": "^5.3.0"
}
}
Could it be that the .otf file format isn't supported by Expo?
I fixed this issue by converting the otf files to ttf
I had a similar issue and I was able to resolve it by removing the quotes around the key that requires the font source.
Before:
await Font.loadAsync({
"Light": require('./assets/fonts/SemplicitaPro-Light.otf')
})
After
await Font.loadAsync({
Light: require('./assets/fonts/SemplicitaPro-Light.otf')
})
And using it in the stylesheet like so
const styles = StyleSheet.create({
text: {
fontFamily: 'Light'
}
});
Everything worked fine after that.
I'm building a React/Redux/ReactRouter/Jest boilerplate but I'm having an issue when testing a component with react-test-renderer.
I have put in place two kind of tests: unit tests for my redux actions and snapshot tests as a form of functional tests for my components.
First of all, my unit tests work perfectly. Here's one:
import mockStore from 'redux-mock-store';
import {fetchWordDefinitions} from '../src/actions';
describe('Async fetch of word definitions', () => {
it('fetches a word definitions', async () => {
const mockedResponse = [
{text: 'First definition'},
{text: 'Second definition'},
{text: 'Third definition'}
];
fetch.mockResponse(JSON.stringify(mockedResponse));
const store = mockStore({});
await store.dispatch(fetchWordDefinitions('whatever'));
expect(store.getActions()).toEqual([
{type: 'ERROR', error: null},
{type: 'FETCHING', fetching: true},
{
type: 'WORD_DEFINITIONS',
word: 'whatever',
definitions: [
"First definition",
"Second definition",
"Third definition"
]
},
{type: 'FETCHING', fetching: false}
]);
});
});
As you can see I'm using ES6 there (both in the test and in the tested action) and everything works fine.
The problem is when I try to test a component by creating it with react-test-renderer. Here's the broken test:
import React from 'react';
import {Provider} from 'react-redux';
import renderer from 'react-test-renderer';
import mockStore from 'redux-mock-store';
import Home from './../src/containers/Home';
test('test', () => {
const store = mockStore({});
const container = renderer.create(
<Provider store={store}>
<Home/>
</Provider>
);
// some assertions - execution does not get here
});
Here's what I get in the CLI:
FAIL __tests__/Home.test.js
● Test suite failed to run
/data/src/containers/Home.js: Unexpected token (8:11)
6 |
7 | class Home extends ReduxComponent {
> 8 | search = (value) => {
| ^
9 | if (value !== this.status().selectedWord) {
10 | this.dispatch(fetchRelatedWords(value));
11 | }
And this is my .babelrc file (which is sitting in the root of my project folder):
{"presets": ["es2015", "react"]}
And finally the packages.json file:
{
"name": "vocabulary",
"version": "0.1.0",
"author": "Francesco Casula <fra.casula#gmail.com>",
"license": "MIT",
"private": false,
"dependencies": {
"prop-types": "^15.5.8",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-redux": "^5.0.4",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"redux": "^3.6.0",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-jest": "^19.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"jest-fetch-mock": "^1.0.8",
"react-scripts": "^0.9.5",
"react-test-renderer": "^15.5.4",
"redux-logger": "^3.0.1",
"redux-mock-store": "^1.2.3",
"regenerator-runtime": "^0.10.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "jest"
},
"jest": {
"verbose": true,
"setupFiles": [
"./config/jest/setup.js"
]
}
}
By looking at the error it seems like babel may not be doing its magic?
What I find weird though is that is transpiling correctly in the other tests (the action ones).
Hope you guys can help me figure this out :-)
You will need the class-properties transform. Class properties are not yet in the ECMAScript spec but there are Babel plugins to allow this behavior.