Apollo Client - How to test a component that uses multiple queries, using HOC components that use compose - reactjs

I am reading over the docs for testing React/Apollo components Link. If the component has one query, it seems pretty simple to test it.
const mocks = [
{
request: {
query: GET_DOG_QUERY,
variables: {
name: 'Buck',
},
},
result: {
data: {
dog: { id: '1', name: 'Buck', breed: 'bulldog' },
},
},
},
];
it('renders without error', () => {
renderer.create(
<MockedProvider mocks={mocks} addTypename={false}>
<Dog name="Buck" />
</MockedProvider>,
);
});
My component is a little different than the one provided in the documentation.
It doesn't use the useQuery hook, instead I am opting for the HOC approach as outlined here.
I have two queries that my function uses, and so I use two graphql functions and combine them together using compose, as recommended in the docs.
My component is exported like this:
export default compose(withQueryA, withQueryB)(MyComponent);
const withQueryA = graphql(QUERY_A, {
name: "QueryA",
options: (props) => ({
variables: {
foo: props.foo,
},
}),
});
const withQueryB = graphql(QUERY_B, {
name: "QueryB ",
options: (props) => ({
variables: {
bar: props.bar,
},
}),
});
What I'm trying to do is provide the mocks object with multiple objects, each containing a request/result for the corresponding query. I just wanted to know if anyone has been testing their components in a similar way or if there is a better suggestion.
const mocks = [
{
request: {
query: QUERY_A,
variables: {
foo: "bar",
},
},
result: {
data: {
...,
},
},
},
{
request: {
query: QUERY_B,
variables: {
foo: "bar",
},
},
result: {
data: {
...,
},
},
},
];
I'm also confused about what to put in the result object. When I console.log what is actually returned to the component when making a query in production, it has the data plus error, fetchMore, loading, networkStatus. Do I have to put all those things in the mocks as well?

My feeling was correct. The result object should look something like this:
const mocks = [
{
request: {
query: QUERY_A,
variables: {
foo: "bar",
},
},
result: {
data: {
...,
},
},
},
{
request: {
query: QUERY_B,
variables: {
foo: "bar",
},
},
result: {
data: {
...,
},
},
},
];

Related

how to refactoring $expr, $regexMatch filter for easier reading React/MongoDB?

I would like to explain my problem of the day.
Currently I perform a filter on an input which allows me to search the last name and first name it works really well
I have deleted a lot of things for a simpler reading of the code if there is a need to bring other element do not hesitate to ask
const {
data: packUsersData,
} = useQuery(
[
"pack",
id,
"users",
...(currentOperatorsIds.length ? currentOperatorsIds : []),
value,
],
async () => {
const getExpr = () => ({
$expr: {
$or: [
{
$regexMatch: {
input: {
$concat: ["$firstName", " ", "$lastName"],
},
regex: value,
options: "i",
},
},
{
$regexMatch: {
input: {
$concat: ["$lastName", " ", "$firstName"],
},
regex: value,
options: "i",
},
},
],
},
});
let res = await usersApi.getrs({
pagination: false,
query: {
"roles.name": "operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
$or: value
? [
{
entities: [],
...getExpr(),
},
{
entities: { $in: id },
...getExpr(),
},
]
: [
{
entities: [],
},
{
entities: { $in: id },
},
],
},
populate: "entity",
sort: ["lastName", "firstName"],
});
{
refetchOnMount: true,
}
);
and so i find the read a bit too long have any idea how i could shorten all this?
thx for help.
You can reduce entities field $or condition, just concat the empty array and input id,
let res = await usersApi.getrs({
pagination: false,
query: {
"roles.name": "operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
entities: { $in: [[], ...id] },
...getExpr()
},
populate: "entity",
sort: ["lastName", "firstName"]
});
If you want to improve the regular expression condition you can try the below approach without using $expr and aggregation operators,
create a function and set input searchKeyword and searchProperties whatever you want to in array of string
function getSearchContiion(searchKeyword, searchProperties) {
let query = {};
if (searchKeyword) {
query = { "$or": [] };
const sk = searchKeyword.trim().split(" ").map(n => new RegExp(n, "i"));
searchProperties.forEach(p => {
query["$or"].push({ [p]: { "$in": [...sk] } });
});
}
return query;
}
// EX:
console.log(getSearchContiion("John Doe", ["firstName", "lastName"]));
Use the above function in query
let res = await usersApi.getrs({
pagination: false,
query: Object.assign(
{
"roles.name": "operator",
_id: { $nin: currentOperatorsIds },
deletedAt: null,
entities: { $in: [[], ...id] }
},
getSearchContiion(value, ["firstName", "lastName"])
},
populate: "entity",
sort: ["lastName", "firstName"]
});

How to get object in deeply nested array in mongoose using nodes

In my collection of users I have the following
{
_id: ObjectId('whatever user id'),
movies: [
{
_id: ObjectId('whatever id of this movie'),
name: 'name of this movie',
actors: [
{
_id: ObjectId('whatever id of this actor'),
name: 'name of this actor'
}
]
}
]
}
So in my users collection I want to be able to query for a actor by the user.id, pet.id, and the actor.id
I want to return the actor somewhat like this...
actor: {
fields...
}
I tried the following...
const actor = await User.findById(req.user.id, {
movies: {
$elemMatch: {
_id: req.params.movie_id,
actors: {
$elemMatch: {
_id: req.params.actor_id,
},
},
},
},
});
I have tried other things but can't seem to get it to work. I saw that you can maybe use aggregate but I am not sure how to query that while using the ids I have at my disposal.
I was able to figure it out by using aggregate. I was using this before but it seems that I needed to cast my ids with mongoose.Types.ObjectId so a simple req.user.id would not work.
In order to get my answer I did...
const user = await User.aggregate([
{ $match: { _id: mongoose.Types.ObjectId(req.user.id) } },
{ $unwind: '$movies' },
{ $match: { 'movies._id': mongoose.Types.ObjectId(req.params.movie_id) } },
{ $unwind: '$movies.actors' },
{
$match: {
'movies.actors._id': mongoose.Types.ObjectId(req.params.actor_id),
},
},
]);
This did not return data in the following format...
actor: {
fields...
}
but returns it instead like this...
user: {
movies: {
actor: {
fields...
}
},
otherFields...
}
then sending the response back...
res.status(200).json({
status: 'success',
data: {
actor
}
})
gives that format I wanted. However, I would still want to know how to just get the data actor without getting the full document

Create a custom element in EditorJs

I added EditorJs plugin in my react js application:
import ReactDOM from "react-dom";
import React, { Component } from "react";
import EditorJs from "react-editor-js";
import { EDITOR_JS_TOOLS } from "./constants";
class ReactEditor extends Component {
render() {
return (
<EditorJs
tools={EDITOR_JS_TOOLS}
data={{
blocks: [
{
type: "header",
data: {
text: "Editor.js",
level: 2
}
},
{
type: "paragraph",
data: {
}
},
{
type: "header",
data: {
text: "Key features",
level: 3
}
},
{
type: "list",
data: {
style: "unordered",
items: [
"It is a block-styled editor",
"It returns clean data output in JSON",
"Designed to be extendable and pluggable with a simple API"
]
}
},
{
type: "header",
data: {
text: "What does it mean «block-styled editor»",
level: 3
}
},
{
type: "paragraph",
data: {
text:
'Workspace in classic editors is made of a single contenteditable element, used to create different HTML markups. Editor.js <mark class="cdx-marker">workspace consists of separate Blocks: paragraphs, headings, images, lists, quotes, etc</mark>. Each of them is an independent contenteditable element (or more complex structure) provided by Plugin and united by Editor\'s Core.'
}
},
{
type: "paragraph",
data: {
text:
'There are dozens of ready-to-use Blocks and the simple API for creation any Block you need. For example, you can implement Blocks for Tweets, Instagram posts, surveys and polls, CTA-buttons and even games.'
}
},
{
type: "header",
data: {
text: "What does it mean clean data output",
level: 3
}
},
{
type: "paragraph",
data: {
text:
"Classic WYSIWYG-editors produce raw HTML-markup with both content data and content appearance. On the contrary, Editor.js outputs JSON object with data of each Block. You can see an example below"
}
},
{
type: "paragraph",
data: {
text:
'Given data can be used as you want: render with HTML for <code class="inline-code">Web clients</code>, render natively for <code class="inline-code">mobile apps</code>, create markup for <code class="inline-code">Facebook Instant Articles</code> or <code class="inline-code">Google AMP</code>, generate an <code class="inline-code">audio version</code> and so on.'
}
},
{
type: "paragraph",
data: {
text:
"Clean data is useful to sanitize, validate and process on the backend."
}
},
{
type: "delimiter",
data: {}
},
{
type: "paragraph",
data: {
text:
"We have been working on this project more than three years. Several large media projects help us to test and debug the Editor, to make it's core more stable. At the same time we significantly improved the API. Now, it can be used to create any plugin for any task. Hope you enjoy. 😏"
}
},
{
type: "image",
data: {
file: {
url:
"https://codex.so/upload/redactor_images/o_e48549d1855c7fc1807308dd14990126.jpg"
},
caption: "",
withBorder: true,
stretched: false,
withBackground: false
}
}
],
version: "2.12.4"
}}
/>
);
}
}
ReactDOM.render(<ReactEditor />, document.getElementById("root"));
According to the documentation i can create a custom element:
render() {
return (
<EditorJs holder="custom">
<div id="custom" />
</EditorJs>
);
}
Question: I want to add as a custom element an input: <input type="text"/>, but i don't manage even if i do:
<EditorJs holder="custom">
<input id="custom" type="text"/>
</EditorJs>
Who knows how to add this custom element in the plugin above?
demo: https://codesandbox.io/embed/react-editor-js-23opz
I found in the documentation that i can create a plugin for editor.js:
https://editorjs.io/the-first-plugin. One of example looks like this:
class SimpleImage {
static get toolbox() {
return {
title: 'Image',
icon: '<svg width="17" height="15" viewBox="0 0 336 276" xmlns="http://www.w3.org/2000/svg"><path d="M291 150V79c0-19-15-34-34-34H79c-19 0-34 15-34 34v42l67-44 81 72 56-29 42 30zm0 52l-43-30-56 30-81-67-66 39v23c0 19 15 34 34 34h178c17 0 31-13 34-29zM79 0h178c44 0 79 35 79 79v118c0 44-35 79-79 79H79c-44 0-79-35-79-79V79C0 35 35 0 79 0z"/></svg>'
};
}
render() {
return document.createElement('input');
}
save(blockContent) {
return {
url: blockContent.value
}
}
}

React Axios Get Call to Output JSON Format

I am performing an Axios get call in a React Component to retrieve JSON info. That function is working great. Within the JSON is a label for various network ports, which are returning as an array in my axios call. These are ultimately going to be displayed as nodes on a d3 graph. My issue is that I need to output the data pulled from the get call into the following format:
nodes: [
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' }
]
So the full component for the graph to read is:
export const data = {
nodes: [
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' },
{ id: 'JSON data.label here' }
]
}
Here is the format of the Axios get I am using:
axios.get(`NetworkConstruct.json`)
.then(res => {
const names = res.data.items;
this.setState({ names });
});
Here is a sample output I am receiving (there are 11 of these):
{id: "5bc0860c-ece1-461c-bac0-b155a3cacd82", label: "80.107.0.212",
resourceTypeId: "tosca.resourceTypes.NetworkConstruct", productId:
"5bc0835c-6cfa-486e-8429-a59eaf4118bc", tenantId: "393fa8da-61fd-458c-80f9-
ce92d0ef0330", …}
The data has to be in this EXACT format or the graph won't read it. I'm guessing I'll need to do an initial map function but am stuck on how to arrange it. I cannot have any divs or quotes in my output. Is this doable? I have scoured the boards and Google for a couple of days and can't make this work yet.
Here is the object I am receiving from the GET request.
{
"id": "5bd2c6ef-6009-4b90-9156-62168f3c6293",
"resourceId": "5bd0ba82-2994-455d-8716-2adb5694d6f0",
"interface": "getGraph",
"inputs": {},
"outputs": {
"graph": {
"nodes": [
{
"id": "5bcdf06c-dd53-4335-840f-55a4b8d85a2d",
"name": "asw-lab9306b",
"ports": {
"GigabitEthernet3/0/8": "5bd1777f-0ab9-4552-962b-9e306ce378ab",
"GigabitEthernet2/0/15": "5bd1777e-119c-44e8-ba69-0d86a481c0f5",
"GigabitEthernet3/0/47": "5bd17783-be94-4aaf-8858-70e4eb3d02dc",
"GigabitEthernet2/0/13": "5bd17783-ed99-453f-a958-f764edaa8da8"
}
}
],
"links": [
{
"a": "5bd1a467-13f2-4294-a768-561187b278a8",
"z": "5bd17770-2e6c-4c37-93c8-44e3eb3db6dd",
"layer": "ETHERNET"
},
{
"a": "5bd1776e-c110-4086-87d6-a374ccee419a",
"z": "5bd17770-83ee-4e10-b5bb-19814f9f5dad",
"layer": "ETHERNET"
}
]
}
},
"state": "successful",
"reason": "",
"progress": [],
"providerData": {},
"createdAt": "2018-10-26T07:49:03.484Z",
"updatedAt": "2018-10-26T07:49:25.425Z",
"resourceStateConstraints": {},
"executionGroup": "lifecycle"
}
The info I need is the nodes ID. There are eleven of them in the full object.
You can map an array of objects to another array of objects in your format with Array.prototype.map(). Assuming that data is the list of objects from your response:
class Graph extends React.Component {
state = {
nodes: null,
};
componentDidMount() {
axios.get('the url').then(response => {
const nodes = response.data.outputs.graph.nodes;
this.setState({nodes});
});
}
render() {
const {nodes} = this.state;
if (!nodes) return 'Loading...'
return <TheD3ComponentYouUse nodes={nodes} />;
}
}

reactjs action creators pass an array

How to pass set of arrays in an object from a react component for a post request: This should be the structure of my request object:
{
"test": [
"abc"
],
"test2": [
"def"
],
"test3": [
"sds"
],
"name": "sam"
}
getting error when I do:
React Component:
this.props.actioncreatorCall(
someurl,
["abc"],
["def"],
["sasd"],
"sam"
);
Action creator:
export function apiCAll(someurl,{test, test2, test3, name}) {
return function dispatchUser(dispatch) {
axios.post((url),{test,
test2,
test3,
name},{ },
).then((response) => {
dispatch({
type: DATA_POST,
payload: response.data,
});
browserHistory.push('/NEXTPAGE');
})
.catch(() => {
//SOME ERROR
});
};
}
You need to pass in the second param as an object:
this.props.actioncreatorCall(someurl,{
test: ["abc"],
test2: ["def"],
test3: ["sasd"],
name: "sam"
});
And you action creator needs to accept an object as the second param:
export function actioncreatorCall(someurl, test = {}) {...}

Resources