AntDesign validation Typography editable text - regex

I'm trying to validate when the user is typing in the Antd Design Text, so that it does not let him write other value than numbers and onchange does not return anything.
"antd": "^4.3.3",
"react": "^16.13.1"
import React from "react";
import { Typography } from "antd";
const { Text } = Typography;
export default class Demo extends React.Component {
state = {
price: 0,
};
onChange = (price) => {
let isValid= validatePriceRegex(price);
console.log(isValid, "Price:", price);
this.setState({ price});
};
handleChange = (e) => {
// In this part, I want to validate the input when the user is typing the value
console.log(e); // dont return anything
};
render() {
return (
<Text
onChange={this.handleChange}
editable={{ onChange: this.onChange }}
>
{this.state.price.toString()}
</Text>
);
}
}
const validatePriceRegex = (price) => {
const regex = /^\$?\d+(,\d{3})*(\.\d*)?$/;
return price && regex.test(price);
};

you seems to have 2 handle on change function. the handleChange and the handleChange
editable Text component only accepts onChange inside of the editable props, so you have to do in the same on change function
import React from "react";
import { Typography } from "antd";
const { Text } = Typography;
export default class Demo extends React.Component {
state = {
price: 0
};
onChange = price => {
let isValid = validatePriceRegex(price);
console.log(isValid, "Price:", price);
// you validate here
if (isValid) {
this.setState({ price });
}
};
// handleChange = e => {
// // In this part, I want to validate the input when the user is typing the value
// console.log(e); // dont return anything
// };
render() {
return (
<Text editable={{ onChange: this.onChange }}>
{this.state.price.toString()}
</Text>
);
}
}
const validatePriceRegex = price => {
const regex = /^\$?\d+(,\d{3})*(\.\d*)?$/;
return price && regex.test(price);
};

Related

How to test `dangerouslySetInnerHTML` attribute with Testing Library and Jest?

I have a component called Previewer :
export const createMarkup = (htmlStr: string) => {
return { __html: marked(htmlStr, markedConfig) };
};
export const Previewer = ({ content }: Props) => {
return (
<div
id='preview'
dangerouslySetInnerHTML={createMarkup(content)}
role='textbox'
></div>
);
};
I want to test if that div has an attribute called dangerouslySetInnerHTML and display the provided text:
test("should return a div with an id = preview", () => {
const defaultContent = "# Welcome to React Markdown";
render(<Previewer content={defaultContent} />);
const element = screen.getByRole("textbox");
expect(element).toHaveAttribute("id", "preview"); // passed
expect(element).toHaveAttribute("dangerouslySetInnerHTML", createMarkup(defaultContent)); // failed
});

TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')

Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
App.js
import { StyleSheet, Text, View, StatusBar, PermissionsAndroid, Platform,} from 'react-native';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import DestinationSearch from './src/screens/DestinationSearch/DestinationSearch';
import SearchResults from './src/screens/SearchResults/SearchResults';
import { useEffect, useState } from 'react';
//import * as Location from 'expo-location';
import Geolocation, { getCurrentPosition } from 'react-native-geolocation-service';
navigator.geolocation = require('react-native-geolocation-service');
export default function App() {
const androidPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Uber App location Permission",
message:
"Uber App needs access to your location " +
"so you can take awesome rides.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location");
} else {
console.log("Location permission denied");
}
} catch (err) {
console.warn(err);
}
};
useEffect(() => {
if (androidPermission) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
}, [])
useEffect(() => {
if(Platform.OS == 'android') {
androidPermission()
} else{
//IOS
Geolocation.requestAuthorization();
}
}, [])
return (
<View>
{/* <HomeScreen /> */}
<DestinationSearch />
{/* <SearchResults /> */}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop:StatusBar.currentHeight
},
});
`
DestinationSearch.jsx
import { View, Text, StyleSheet, SafeAreaView, StatusBar } from 'react-native'
import React, {useEffect, useState,} from 'react'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import {GOOGLE_MAPS_APIKEY} from '#env'
import PlaceRow from './PlaceRows';
const DestinationSearch = () => {
const [originPlace,setOriginPlace] = useState(null)
const [destinationPlace, setDestinationPlace] = useState(null)
useEffect(() => {
console.log('useEffect is called')
if (originPlace && destinationPlace) {
console.warn('Redirect to results')
}
}, [originPlace, destinationPlace])
return (
<SafeAreaView>
<View style={styles.container}>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'From...'
listViewDisplayed = 'auto'
debounce = {400}
currentLocation = {true}
currentLocationLabel='Current location'
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
renderRow={(data)=> <PlaceRow data={data}/>}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
styles={{
container: styles.autocompleteContainer,
textInput: styles.textInput,
listView: styles.listView,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setOriginPlace({data, details})
console.log(currentLocation)
}}
/>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'To...'
listViewDisplayed = 'auto'
debounce = {400}
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
renderRow={(data)=> <PlaceRow data={data}/>}
styles={{
container: {
...styles.autocompleteContainer,
top: 70
},
textInput: styles.textInput,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setDestinationPlace({data, details})
}}
/>

How can I mock a paginated GraphQL query?

I am using apollo/client and graphql-tools/mock to auto mock graphql queries and test React Native components that use them. My schema is generated from an introspection query created by graphql-codegen. For the most part, my queries are getting mocked by addMocksToSchema just fine. However I have a query that is not returning any mock data.
The query is paginated and doesn't follow the same structure of the examples in the docs (https://www.graphql-tools.com/docs/mocking). Instead of having a query with a node that has a field that is a connection type, the connection is returned from the query. This means I can't use relayStylePaginationMock to mock my function because the resolver argument of addMocksToSchema expects the nodes to be objects not functions(function is the return type of relayStylePaginationMock).
In the below code I have tried overriding the newsPost query with a resolver, but I can't figure out how to get the NewsPostEdges from the store and put them in my mock. Everything I have tried has broken the mock and caused it to return undefined for the whole mocked query.
Why does a paginated mock not work by default?
How can I mock this query?
Schema:
type Query {
newsPost: NewsPostConnection
}
type NewsPostConnection {
totalCount: Int
edges: [NewsPostEdge]!
pageInfo: PageInfo!
}
type NewsPostEdge {
node: NewsPostNode
cursor: String!
}
type NewsPostNode {
newsPostId: Int!
isPinned: Boolean!
label: String
title: String
content: String
postType: NewsPostType!
createdDate: DateTime
createdDateTime: String
creator: UserNode!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
endCursor: String
startCursor: String
}
News Posts query:
query NewsPosts(
$after: String
$first: Int
$newsPostId: Filter_ID
$sort: [NewsPostSortEnum]
$isPinned: Filter_Boolean
) {
newsPosts(
after: $after
first: $first
newsPostId: $newsPostId
sort: $sort
isPinned: $isPinned
) {
pageInfo {
hasNextPage
endCursor
}
edges {
post: node {
newsPostId
postType
isPinned
label
createdDateTime
creator {
initials
avatarUrl
displayName
}
content
}
}
}
}
newsPostsContent.test.tsx
import React from 'react';
import { waitFor } from '#testing-library/react-native';
import { PartialDeep } from 'type-fest';
import { faker } from '#faker-js/faker';
import { createFakeUser, render } from '#root/unit-tests/#util';
import { NewsPostNode, NewsPostType } from '#root/src/generated';
import NewsPostContent from '../NewsPostContent';
const mocks = {
NewsPostNode: (): PartialDeep<NewsPostNode> => {
const postId = faker.random.numeric(4);
const createdDate = faker.date.recent(10);
return {
postId,
isPinned: true,
label: 'test',
content: `<div><p>${faker.random.words(10)}</p></div>`,
postType: NewsPostType.Announcement,
createdDate: createdDate.toISOString(),
createdDateTime: createdDate.toISOString(),
};
},
UserNode: createUserPerson(),
};
describe('Dashboard News', () => {
it('renders dashboard news', async () => {
const { getByTestId, debug } = render(
<NewsPostContent />,
mocks,
);
await waitFor(() => [debug(), expect(getByTestId('newsPostContent:Card')).toBeDefined()]);
});
});
NewsPostsContetnt.tsx
const NewsPostContent = () => {
const [newsPostList, setNewsPostList] = useState<PartialDeep<NewsPostNode>[]>([])
const {
data,
loading,
refetch: refetchPosts,
} = useNewsPostsQuery({
variables: { first: MAX_POSTS, isPinned: true, sort: [PostSortEnum.CreatedDateDesc] },
});
console.log(data); // <-- returns undefined when mock breaks
useEffect(() => {
const newsPostEdges = data?.newsPosts?.edges ?? [];
const newsPostNodes = newsPostEdges.reduce((posts, newsPostNode) => {
if (newsPostNode?.post) {
posts.push(newsPostNode.post);
}
return posts;
}, [] as PartialDeep<NewsPostNode>[]);
setNewsPostList(newsPostNodes);
}, [data]);
return (
{<View>
// Component UI to render posts
</View>}
)
}
AutoMockedProvider.tsx
import React from 'react';
import { ApolloProvider, ApolloClient, InMemoryCache } from '#apollo/client';
import { buildClientSchema } from 'graphql';
import {
addMocksToSchema,
createMockStore,
IMocks,
IMockStore,
relayStylePaginationMock,
} from '#graphql-tools/mock';
import { SchemaLink } from '#apollo/client/link/schema';
import { faker } from '#faker-js/faker';
const introspectionResult = require('../../src/generated/introspection.json');
const defaultMocks = {
Date: () => faker.date.recent().toISOString(),
DateTime: () => faker.date.recent().toISOString(),
};
const resolvers = (store: IMockStore) => ({
Query: {
newsPosts: (root, { isPinned, after, first, postId, sort }) => {
return {
edges: (ref) => {
const connectionsRef = store.get('NewsPostConnection');
const edgesRef = store.get(connectionsRef, 'edges');
return edgesRef; // <-- this breaks the mock
},
pageInfo: {
endCursor: null,
hasNextPage: false,
},
};
},
},
});
const AutoMockedProvider = ({
mocks = {},
children,
}: React.PropsWithChildren<{ mocks?: IMocks }>) => {
const schema = buildClientSchema(introspectionResult);
const store = createMockStore({ mocks: { ...defaultMocks, ...mocks }, schema });
const schemaWithMocks = addMocksToSchema({
schema,
mocks: {
...defaultMocks,
...mocks,
},
resolvers,
preserveResolvers: false,
store,
});
const client = new ApolloClient({
link: new SchemaLink({ schema: schemaWithMocks }),
cache: new InMemoryCache(),
});
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};
export default AutoMockedProvider;

Why is React not displaying any data?

import React, { Component } from 'react';
import axios from 'axios';
I would like to display this on the page:
class ProjectDeatil extends Component {
constructor(props) {
super(props);
this.state = { user: { name: '' } };
}
.
componentDidMount() {
const { match: { params } } = this.props;
axios.get(`http://localhost:8000/api/project/${params.pk}`)
.then(({ data: user }) => {
console.log( user);
this.setState({"User:": user });
});
}
I added her const
render() {
const{ user } = this.state;
return (
Then I tried displaying it again and it still didn't work
<div className="col-md-4 text-white animated fadeInUp delay-2s if " >
<h1>{user.title}</h1>
<h1> Hello Dear</h1>
</div>
I also tried using django rest api and that also didn't work.
</div>
);
}
}
export default ProjectDeatil
You have to fix this line:
this.setState({"User:": user });
to
this.setState({"user": user });

How to mock Picker and Picker.Item with jest in React-Native?

I am trying to snapshot test this snippet of code:
import React, { Component } from 'react';
import {
Picker,
} from 'react-native';
export default class TestComponent extends Component {
render() {
return (
<Picker
selectedValue={this.props.asset.type}
onValueChange={this.props.onTypeChange}>
<Picker.Item label="Type of asset" value="default" />
<Picker.Item label="Car" value="car" />
<Picker.Item label="Boat" value="boat" />
<Picker.Item label="Ship" value="ship" />
</Picker>
);
}
}
My test looks like this right now:
import 'react-native';
import React from 'react';
import TestComponent from './TestComponent';
import renderer from 'react-test-renderer';
describe('TestComponent', () => {
const asset = {
type: 'car',
}
it('renders correctly', () => {
const tree = renderer.create(
<TestComponent
asset={asset} />
).toJSON();
expect(tree).toMatchSnapshot();
});
})
My problem is that I get:
TypeError: Cannot read property '_tag' of undefined
I think that I should mock it based on this issue
I have tried adding simply:
jest.mock('Picker', () => 'Picker')
But than it still throws an error because Picker.Item is still not mocked
Invariant Violation: Element type is invalid: expected a string (for built-
in components) or a class/function (for composite components)
but got: undefined. Check the render method of `TestComponent`.
Other variants I tried with no avail:
jest.mock('Picker', () => {return {Item: 'Item'}});
----------------------------------------------------
class Picker{
Item = 'PickerItem'
}
jest.mock('Picker', () => {
return Picker;
});
Created a github issue as well and here is a working answer:
jest.mock('Picker', () => {
const Picker = class extends Component {
static Item = props => React.createElement('Item', props, props.children);
static propTypes = { children: React.PropTypes.any };
render() {
return React.createElement('Picker', this.props, this.props.children);
}
}
return Picker;
})
For Expo v39, I was able to test #react-native-community/picker by adding the following mock to my test/setup file:
jest.mock('#react-native-community/picker', () => {
const React = require('React')
const RealComponent = jest.requireActual('#react-native-community/picker')
class Picker extends React.Component {
static Item = (props: { children: never }) => {
return React.createElement('Item', props, props.children)
}
render () {
return React.createElement('Picker', this.props, this.props.children)
}
}
Picker.propTypes = RealComponent.propTypes
return {
Picker
}
})
Note that #react-native-community/picker is now react-native-picker/picker.
https://jestjs.io/docs/en/tutorial-react-native#tips