Issue integrating Jest into React application - testing

I recently created a react application and would like to test it. I am trying to use Jest as Facebook recommends but have run into an issue. The specific error is as follows:
FAIL __tests__/popup-test.js
● Runtime Error
SyntaxError: Unexpected token [
at Function (native)
at Array.forEach (native)
at Array.forEach (native)
npm ERR! Test failed. See above for more details.
The code for popup-test.js
'use strict';
jest.unmock('../dist/test/popup.js');
const React = require('react');
const ReactDOM = require('react-dom');
const TestUtils = require('react-addons-test-utils');
let Popup = require('../dist/test/popup.js');
describe('Popup', () => {
it('works', () => {
var popupTest = TestUtils.renderIntoDocument(
<Popup />
);
var popupNode = ReactDOM.findDOMNode(popupTest);
expect(1).toEqual(1);
});
});
As you can see, the error does not provide me with any information. I know the problem is with requiring my popup file and I can post the contents of the code here. I was hoping though that someone had encountered this problem before and could guide me in the right direction to solving it.
Best,
Aneury Casado

Related

Expo-Auth session is not working properly

While implementing google login using the expo-auth-session package , I am getting some error that i don't have any idea about, It has been more than one day since i am stuck in this problem i cannot find a reliable source to use for implementing google login in my expo application. Is there any other way i can implement it in the react native expo application.
The error i am getting are :
WARN Linking requires a build-time setting `scheme` in the project's Expo config (app.config.js or app.json) for production apps, if it's left blank, your app may crash. The scheme does not apply to development in the Expo client but you should add it as soon as you start working with Linking to avoid creating a broken build. [Learn more][1]:
WARN EventEmitter.removeListener('url', ...): Method has been deprecated. Please instead use `remove()` on the subscription returned by `EventEmitter.addListener`.
WARN Possible Unhandled Promise Rejection (id: 2):
Error: Exception in HostFunction: Malformed calls from JS: field sizes are different.
What should i do ??
The link to the documentation that i followed is :-
And this is what i used from the documentation.
import * as Google from "expo-auth-session/providers/google";
import * as WebBrowser from "expo-web-browser";
WebBrowser.maybeCompleteAuthSession();
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: expoClientId,
});
const login = ()=>{
useEffect(() => {
if (response?.type === "success") {
const { authentication } = response;
console.log(authentication);
}
}, [response]);
return (
<Pressable style={styles.btn} onPress={promptAsync}>
<Image
source={require("../../../assets/g1.png")}
style={styles.img}
/>
<Text style={styles.text}>Sign in with Google</Text>
</Pressable>
)
}
thank you any help would be appriciated.
In your app.json add following
"scheme":"com.yourpackage.yourapp"
this value must be same as your android.package and ios.bundleIdentifier

Expo React Native: Code Splitting Incompatible Web Packages

I have a component that uses #stripe/stripe-react-native named NativeCheckout.
This package does not work on web (Chrome), and when I import it I get an error:
Failed to compile
/home/joey/Projects/project/project_frontend/node_modules/#stripe/stripe-react-native/lib/module/components/StripeProvider.js
Module not found: Can't resolve '../../package.json' in '/home/joey/Projects/project/project_frontend/node_modules/#stripe/stripe-react-native/lib/module/components'
So if I run it in my browser, I do not want this component. This component is only rendered on native apps. I have found three alternative ways to import the Component. If my code is working fine then I add any of the follow lines, the above error is happening. I thought this would not load in the problem code.
const loadNative = async () => {
await import("./NativeCheckout")
}
const NativeCheckout = lazy(() => import("./NativeCheckout"));
const NativeCheckout = lazy(() => import("./NativeCheckout"));
Does anyone know a way to make this work?
TIA

mainBundlePath is Null for node package

I am using the package react-native-coreml and running into this error at startup.
My intention is to use this package to use a CoreML package in my react native app. I am running this within EXPO if that makes any difference.
I can't even run the app. These two errors are together.
Unable to start your application. Please refer to https://expo.fyi/no-registered-application for more information.
and
TypeError: null is not an object (evaluating 'RNCoreML.mainBundlePath')
- node_modules/react-native/Libraries/LogBox/LogBox.js:148:8 in registerError
Obviously the first error isn't useful, just including for thoroughness.
My implementation is as follows:
import React, { useState } from 'react'
import { StyleSheet, Text, View } from 'react-native'
import FaceScanner from './FaceScanner';
import { classifyImage } from "react-native-coreml";
const Onboarding = () => {
const [imageURL, setImageURL] = useState('');
const [tested, setTested] = useState(false);
console.log(imageURL)
if (imageURL !== '' && !tested) {
async () => {
// const { label, confidence } = await classifyImage(imageURL, './model.mlmodelc')
setTested(true);
console.log("The image is a " + label + ". I think. ")
}
}
...
edit I have ejected from expo as per a comment's suggestion. I am now encountering these errors.
BUNDLE ./index.js
ERROR TypeError: null is not an object (evaluating 'RNCoreML.mainBundlePath')
LOG Running "main" with {"rootTag":1,"initialProps":{}}
ERROR Invariant Violation: "main" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.
react-native-coreml is a library with native extensions that do not work in the expo managed workflow currently. you can read about the managed workflow limitations in the expo docs.
if you'd like to use it, run expo eject and build the project in xcode

How to use enzyme for react-native with jest

I have followed –or tried to– several posts on how to do it, including the airbnb enzyme's guide for (separatedly) react-native and jest. (E.g: https://medium.com/#childsmaidment/testing-react-native-components-with-enzyme-d46bf735540#.6sxq10kgt, https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.4iqylmqh5 or How to use Jest with React Native)
But I keep getting lots of warnings (I have multiple set of concurrent tests) whenever I try to render (not mount, it crashes) any native component. Warnings are always about a native prop not being recognised.
Warning: Unknown props `focus`, `secureTextEntry` on <TextInput> tag. Remove these props from the element.
in TextInput (created by TextInput)
in TextInput (created by PasswordInput)
Anyone who has a set up working, recognises how to remove the warning or how to solve it?
Thanks
So I know this is a bit old but I was having issues with Jest, Enzyme, and React Native and I found this post - hopefully this solution will help.
To start with - Enzyme doesn't support mounting React Native and only supports shallow rendering. This wasn't good enough for me as I needed end-to-end tests from the component to the api which lead me to react-native-mock-render. What this does is allow us to run react native inside a browser environment which let's us test using Enzyme - all the calls for React Native and the components work as you would expect.
To set this up you'll need to install JSDOM, react-native-mock-render, Enzyme 3.0+, and Jest 20.0.0+. And then inside your jest setup file (which is specified in your package.json) include the following code:
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM();
const { window } = jsdom;
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
// Setup adapter to work with enzyme 3.2.0
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
// Ignore React Web errors when using React Native
console.error = (message) => {
return message;
};
require('react-native-mock-render/mock');
And that's it - you're all setup to mount components in Enzyme and test them.
If you want to see a full sample check out react-native-mock-render-example. This is working with React 16, React Native 0.51, and Enzyme 3.2.
In order to unit test your component with jest you can use enzyme-to-json
npm install --save enzyme-to-json
then your test would look like this:
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import MyComponent from './MyComponent';
it('should render component', => {
expect(shallowToJson(shallow(<MyComponent />))).toMatchSnapshot();
});
I'm not sure regarding your case with react-native.
I can share my case of using jest + enzyme with standard react.
When I needed to test some component and isolate it from others I used jest.mock, e.g.
jest.mock('../ComponentToBeMocked', () => {
return () => null;
});
Initially I found examples when the second argument (a function) should return just a string representing a name of the mocked component. But in that case I saw that distracting Unknown props warning.

angular2 testing, error in ViewUtils when using setBaseTestProviders()

When using the method 'setBaseTestProviders(..)', an error pops up in the console.
We're using angular-2.0.0-rc.1.
The test (test/areas-list.component.spec.ts) is as follows:
import {setBaseTestProviders} from "#angular/core/testing";
import {ADDITIONAL_TEST_BROWSER_PROVIDERS, TEST_BROWSER_STATIC_PLATFORM_PROVIDERS} from '#angular/platform-browser/testing/browser_static';
import {BROWSER_APP_DYNAMIC_PROVIDERS} from '#angular/platform-browser-dynamic';
setBaseTestProviders([
BROWSER_APP_DYNAMIC_PROVIDERS,
ADDITIONAL_TEST_BROWSER_PROVIDERS,
], TEST_BROWSER_STATIC_PLATFORM_PROVIDERS);
describe('test test', () => {
//Not really important
});
When I open the browser, the following error is shown in the console:
zone.js:323 Error: Error: Cannot resolve all parameters for 'ViewUtils'(RootRenderer, undefined #Inject(Token AppId), SanitizationService). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'ViewUtils' is decorated with Injectable.
at NoAnnotationError.BaseException [as constructor] (http://127.0.0.1:8080/node_modules/#angular/core/src/facade/exceptions.js:17:23)
at new NoAnnotationError (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_exceptions.js:217:16)
at _extractToken (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:232:15)
at eval (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:184:45)
at Array.map (native)
at _dependenciesFor (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:184:19)
at resolveReflectiveFactory (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:72:24)
at resolveReflectiveProvider (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:96:97)
at Array.map (native)
at Object.resolveReflectiveProviders (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:104:31)
Evaluating http://127.0.0.1:8080/test/areas-list.component.spec.js
Error loading http://127.0.0.1:8080/test/areas-list.component.spec.js
Does somebody know what the problem is? Thanks in advance!
Is there any specific case you're trying to achieve with browser static?
Here is the basic config:
import { setBaseTestProviders } from '#angular/core/testing';
import {
TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '#angular/platform-browser-dynamic/testing';
setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);