Categories
DEVELOPMENT TECHNOLOGY

Why go for GraphQL for integration of your modern APIs?

In a survey conducted involving people working with Application Programming Interfaces (APIs) was conducted, 33.4% of respondents said that GraphQL is one of the most exciting technologies to opt for.

GraphQL is developed by Facebook that was initially applied for mobile applications in 2012. In 2015, GraphQL specifications were outsourced, which is now administered by GraphQL Foundation.

What is GraphQL and why is it important for your modern APIs?

GraphQL is a query language and server-side runtime for APIs and a runtime for fulfilling the queries with your existing data. If you need to have a complete understanding of the data in your API, then GraphQL is your best go! 

With GraphQL, clients will have the ability to procure only what they need and nothing more or nothing less. GraphQL controls the data and not the server, and it always returns predictable results! This makes APIs easily flexible, fast, and developer-friendly.

Terms related to GraphQL:

  • Schema: Every possible data that a client can query through a particular service can be described by API developers by creating a schema in GraphQL. A schema consists of object types i.e. the type of object requestable and the fields that it will include.
  • Queries: In GraphQL, queries are  to be validated against the schemas, and only then will the validated queries be executed.
  • Resolver: Resolver is a function to which the developer attaches each field in a schema, with each generator generating a particular value.

What are the decisions that an API developer takes as far as GraphQl is considered? Well, apart from defining and validating syntax for API queries, from the graphql-spec repository, most of the other decisions are presided by the API designer. GraphQL gives no directions regarding how to store data and developers can use any programming language like JavaScript, PHP, Python, Ruby among others. 

From the viewpoint of a client, the most generic GraphQL operations are probably Queries and Mutations. The priority of these operations can be represented in terms of the Create, Read, Update and Delete (CRUD) model, in which Query is equivalent to Reading and Mutations equivalent to Create, Update and Delete.

What are the advantages of GraphQL?

If you are planning to try GraphQL in a business or enterprise environment, here are some reasons for a positive nod:

  1. GraphQL enables an organization to federate its entire API and the GraphQL schema sets a single source of truth in a GraphQL.
  2. In a single round trip, GraphQL calls are managed and clients get the requests they want without any over-fetching.
  3. Data types are strongly defined so there are no communication hassles between the client and the server.
  4. GraphQL is ideal for auto-generating documents because of its introspective feature in which the clients can request a list of data types.
  5. Without breaking existing queries, an application API can be evolved in GraphQL.
  6. Features that are not available with Rest API can be accessed from the open-source GraphQL extensions.
  7.  A particular application architecture need not be dictated, but introduced on top of an already existing Rest API and is workable with existing API management tools.\

What are GraphQL Best Practices?

The GraphQL specifications are purposefully unstated on many critical issues faced by API related to network, authorization, and pagination. It  does not mean that GraphQL has no solutions for these issues, but it simply means that these issues are outside the description of GraphQL. 

The best practices mentioned in the coming section are tactical suggestions for solving recurring issues like serving over HTTP and authorization.

HTTP

While Rest API uses a suite of URLs that expose a single resource, GraphQL is typically served over HTTP through a single endpoint that deliberates a full set of service capabilities. GraphQL is usable alongside a suite of resource URLs but will be a little incompatible with tools like GraphiQL.

JSON GZIP

Despite JSON GZIP not being in the GraphQL specifications, it typically responds to it. JSON is a familiar framework for clients as well as API developers, which is easily readable and debuggable. GraphQL syntax is partially inspired by the JSON syntax.

Versioning

GraphQL avoids versioning by providing resilient tools for the continuous evolution of a GraphQL schema, even though GraphQL can be versioned like any other REST API by all means.

There will be only limited control over the data returned from an API endpoint, any changes can be assumed as a breaking change that requires a new version. The understandability and maintainability of an API becomes difficult with adding new features and constant releases. GraphQL has a different way of dealing with this- it returns those data that are explicit;y requested, without creating a breaking change through adding new types and new fields on those types. Hence this practice is the most opted to avoid breaking changes and serving a version less API.

Nullability

By default, the GraphQL type system has nullable fields. When the network is supported by databases and other services, there are chances that a database crashes or an asynchronous action fails or an exception gets removed. When fields are nullable by default, the fields would return ‘null’ rather than a request failing because of the aforementioned reasons. In the case of GraphQL, when a client raises a request for a non-null field, it will never return null, but will instead set the parent field to ‘null’ when an error occurs.

During the designing phase of GraphQL schema, the designer has to take care of the potential issues if ‘null’ is set as the appropriate value for a failed field.

Pagination

In GraphQL, some fields can  return a list of values. But the -pagination of longer lists of values is left to the decision of the API designer. GraphQL has many API design possibilities for pagination that come with a combination of pros and cons.

APIs feature-efficient paved the way to a best practice pattern termed Connections. Connections tools of clients like Relay can therefore provide automatic support for pagination from the client side when this pattern is integrated by GraphQL.

Server-side batching and caching

Clean codes can be written on the server-side using GraphQL with each field on each type having a focussed on single-purpose function for value resolution. However, there can be repeated data loading from your servers if the GraphQL service is inexperienced or naive. When there are such multiple data requests from the backend in a short period to an underlying database or microservice, the batching technique has opted, and for this tools like DataLoader from Facebook.

Endnote:

Why should companies go for GraphQL? GraphQL is a strong enabler for both API developers and consumers because:

  • Through one unified API, organizations with multiple teams and systems can make their data available easily.
  • There is no under fetching or over fetching of data and can fetch only the required data across the related entities.
  • It has a self-documenting feature that helps to inspect and try out APIs with minimal efforts.
  • It is built around a type system that shows the name and type of each field alongside relationships with different entities.
  • It can encourage different approaches to API modifications.

Want to build an evolvable and queryable API? Then GraphQL is the right choice. With GraphQL, there will be minimal complexity involved for internal systems for data retrieval. It uses a type system that leads to automatic and updated API documentation at all times. Furthermore, its tooling and ecosystem is what qualifies GraphQL as a potential tool not just for the developers, but for your clients too.

Categories
TEKNOLOGI Utveckling

Varför välja GraphQL för integration av dina moderna API:er?

I en undersökning som genomfördes med personer som arbetar med Application Programming Interfaces (API) genomfördes, sa 33,4 % av de tillfrågade att GraphQL är en av de mest spännande teknikerna att välja på.

GraphQL är utvecklat av Facebook som ursprungligen tillämpades för mobilapplikationer 2012. 2015 lades GraphQL-specifikationer ut på entreprenad, som nu administreras av GraphQL Foundation.

Vad är GraphQL och varför är det viktigt för dina moderna API:er?

GraphQL är ett frågespråk och körtid på serversidan för API:er och en körtid för att uppfylla frågorna med dina befintliga data. Om du behöver ha en fullständig förståelse för data i ditt API, är GraphQL det bästa du kan göra! 

Med GraphQL kommer kunder att ha möjligheten att bara skaffa det de behöver och varken mer eller mindre. GraphQL styr data och inte servern, och det ger alltid förutsägbara resultat! Detta gör API:er lätt flexibla, snabba och utvecklar vänliga.

Termer relaterade till GraphQL:

  • Schema: Alla möjliga data som en klient kan fråga genom en viss tjänst kan beskrivas av API-utvecklare genom att skapa ett schema i GraphQL. Ett schema består av objekttyper, dvs den typ av objekt som kan begäras och de fält som det kommer att inkludera.
  • Frågor: I GraphQL ska frågor valideras mot schemana, och först då kommer de validerade frågorna att köras.
  • Resolver: Resolver är en funktion till vilken utvecklaren bifogar varje fält i ett schema, där varje generator genererar ett visst värde.

Vilka är de beslut som en API-utvecklare tar när det gäller GraphQl? Tja, förutom att definiera och validera syntax för API-frågor, från graphql-spec-förrådet, styrs de flesta andra beslut av API-designern. GraphQL ger inga anvisningar om hur man lagrar data och utvecklare kan använda vilket programmeringsspråk som helst som JavaScript, PHP, Python, Ruby med flera. 

Ur en klients synvinkel är de mest generiska GraphQL-operationerna förmodligen frågor och mutationer. Prioriteten för dessa operationer kan representeras i form av Skapa, Läs, Uppdatera och Ta bort (CRUD)-modellen, där Query motsvarar Reading och Mutations som motsvarar Skapa, Uppdatera och Ta bort.

Vilka är fördelarna med GraphQL?

Om du planerar att prova GraphQL i en företags- eller företagsmiljö, här är några anledningar till en positiv nickning:

  1. GraphQL gör det möjligt för en organisation att sammankoppla hela sitt API och GraphQL-schemat sätter en enda källa till sanning i en GraphQL.
  2. På en enda tur och retur hanteras GraphQL-samtal och kunder får de förfrågningar de vill ha utan återhämtning.
  3. Datatyper är starkt definierade så det finns inga kommunikationsproblem mellan klienten och servern.
  4. GraphQL är idealisk för att automatiskt generera dokument på grund av dess introspektiva funktion där klienterna kan begära en lista över datatyper.
  5. Utan att bryta befintliga frågor kan ett applikations-API utvecklas i GraphQL.
  6. Funktioner som inte är tillgängliga med Rest API kan nås från GraphQL-tilläggen med öppen källkod.
  7.  En speciell applikationsarkitektur behöver inte diskuteras, utan introduceras ovanpå ett redan existerande Rest API och är fungerande med befintliga API-hanteringsverktyg.

Vad är GraphQL bästa praxis?

GraphQL-specifikationerna är avsiktligt outtalade för många kritiska frågor som API står inför relaterade till nätverk, auktorisering och sidnumrering. Det betyder inte att GraphQL inte har några lösningar på dessa problem, utan det betyder helt enkelt att dessa problem ligger utanför beskrivningen av GraphQL. 

De bästa metoderna som nämns i det kommande avsnittet är taktiska förslag för att lösa återkommande problem som servering över HTTP och auktorisering.

HTTP

Medan Rest API använder en uppsättning webbadresser som exponerar en enskild resurs, serveras GraphQL vanligtvis över HTTP genom en enda slutpunkt som avser en fullständig uppsättning tjänster möjligheter. GraphQL kan användas tillsammans med en uppsättning resurs-URL:er men kommer att vara lite inkompatibel med verktyg som GraphiQL.

JSON GZIP

Trots att JSON GZIP inte finns i GraphQL-specifikationerna, svarar den vanligtvis på den. JSON är ett välbekant ramverk för såväl klienter som API-utvecklare, som är lätt att läsa och felsöka. GraphQL-syntaxen är delvis inspirerad av JSON-syntaxen.

Versionering

GraphQL undviker versionshantering genom att tillhandahålla motståndskraftiga verktyg för den kontinuerliga utvecklingen av ett GraphQL-schema, även om GraphQL på alla sätt kan versioner som alla andra REST API.

Det kommer endast att finnas begränsad kontroll över data som returneras från en API-slutpunkt, alla ändringar kan antas vara en brytande ändring som kräver en ny version. Det blir svårt att förstå och underhålla ett API när nya funktioner och ständiga utgåvor läggs till. GraphQL har ett annat sätt att hantera detta – det returnerar den data som är explicit efterfrågad, utan att skapa en brytande förändring genom att lägga till nya typer och nya fält på dessa typer. Därför är denna praxis den mest valda för att undvika att bryta ändringar och servera en version mindre API.

Nullbarhet

Som standard har GraphQL-systemet nullbara fält. När nätverket stöds av databaser och andra tjänster finns det chanser att en databas kraschar eller att en asynkron åtgärd misslyckas eller att ett undantag tas bort. När fält är nullbara som standard, skulle fälten returnera “null” istället för att en begäran misslyckas på grund av ovannämnda skäl. I fallet med GraphQL, när en klient ställer en begäran om ett icke-nullfält, kommer den aldrig att returnera null, utan kommer istället att ställa in det överordnade fältet till “null” när ett fel uppstår.

Under designfasen av GraphQL-schemat måste designern ta hand om de potentiella problemen om “null” är inställt som lämpligt värde för ett misslyckat fält.

Paginering

I GraphQL kan vissa fält returnera en lista med värden. Men -pagineringen av längre värdelistor överlåts till API-designerns beslut. GraphQL har många API-designmöjligheter för paginering som kommer med en kombination av för- och nackdelar.

Funktions Effektiva API: er banade vägen för ett bästa praxis mönster som kallas Connections. Anslutningsverktyg för klienter som Relay kan därför ge automatiskt stöd för paginering från klientsidan när detta mönster integreras av GraphQL.

Batchning och cachning

på serversidan Ren Koder kan skrivas på serversidan med hjälp av GraphQL där varje fält på varje typ har en fokuserad på en funktion för värde upplösning. Det kan dock förekomma upprepad dataladdning från dina servrar om GraphQL-tjänsten är oerfaren eller naiv. När det finns så många data förfrågningar från backend under en kort period till en underliggande databas eller mikro tjänst, har batch tekniken valt, och för detta verktyg som Data Loader från Facebook.

Slutnot:

Varför ska företag välja GraphQL? GraphQL är en stark möjliggörare för både API-utvecklare och konsumenter eftersom:

  • Genom ett enhetligt API kan organisationer med flera team och system göra sin data tillgänglig enkelt.
  • Det finns ingen under hämtning eller inhämtning av data och kan endast hämta den nödvändiga informationen över de relaterade enheterna.
  • Den har en självdokumenterande funktion som hjälper till att inspektera och prova API:er med minimala ansträngningar.
  • Den är uppbyggd kring ett typsystem som visar namn och typ av varje fält tillsammans med relationer med olika enheter.
  • Det kan uppmuntra olika tillvägagångssätt för API-modifieringar.

Vill du bygga ett utvecklingsbart och frågekort API? Då är GraphQL rätt val. Med GraphQL kommer det att vara minimal komplexitet involverad för interna system för datahämtning. Den använder ett typsystem som leder till automatisk och uppdaterad API-dokumentation hela tiden. Dessutom är dess verktyg och ekosystem det som kvalificerar GraphQL som ett potentiellt verktyg inte bara för utvecklarna, utan även för dina kunder.

 

Categories
DEVELOPMENT TECHNOLOGY

React Styled-Components: A Run-through

How good are style components in React for styling web pages? If you ask us, we would say it is pretty good!

Adding style to web pages using styled-components has been the practice that brings the quintessential appearance to applications.

So how about we learn a little something about how to style your apps? Let’s get started!

What are the prerequisites?

Do you have the following prerequisites installed and running to follow the coding part?

  • Command line interface running on administrative privileges
  • JavaScript and CSS understanding
  • Yarn or npm package manager
  • Code creator like VS Code of your choice
  • The latest version of Node.JS

What are React and its components?

React is an open-source JavaScript library powered by Facebook Inc. If you are looking forward to building an app in an urbane and responsive User Interface and components, then React is your best course of action. React is one of the most preferred frameworks of front-end developers as it is component-based.

React in the front-end integrates well with backend libraries like Node.JS, Django, Java among others. As a fast, simple, and scalable framework, React extends data changes in your applications without having to reload the applications.

Applications built using React have the provision of developing each of its parts separately and can be reused as a component. React components are reusable JavaScript functions that manage what appears on the UI and the sequence in which it is appearing. The React components return HTML scripts and other pieces built separately as JSX code through the render() function.

These components are then amassed to create complex user interfaces. Additionally, the React components enable developers to segment their application’s UI into independent and reusable sections to engage each section in segregation.

The parts in a web application like navigation bar, search bar, header, and other sections are built as components and merged into a single UI using React components. The components in React can be written as Functions or Classes. Functions or Classes accept defined inputs/props for fixing what is to be delivered on the browsers.

Props are like function arguments that pass data as input from one component to the other. In JavaScript, the functional component takes in single-props as an argument transferred to a component and returns a react element without using the render() method.

In the case of class components, the base component- React. Component- return all defined React elements through the react() method.

In React, buttons, content areas, navigation, dialogue boxes, etc. are a few of the frontend parts that can be defined as components. Now let us see more about React’s styled-components.

Major Styling Strategies in React

How about now we discuss the most popular modern styling strategies in React and how to use them to style your React components? Here are some of the top styling strategies in React:

 

  • CSS and SCSS stylesheets

 

Separate stylesheets are like the traditional way of styling the HTML websites with CSS or CSS preprocessor-SCSS.

 

  • CSS modules

 

CSS modules are CSS files in which all class names alongside animation names are defined in the local setting by default.

 

  • Styled Components

 

Styled-components is a library created for React and React Native developers, enabling them to use component-level styles in their applications. Styled-components are a combination of JavaScript and CSS using the CSS-in-JS technique.

 

  • JSS

 

JSS is an authoring tool for CSS which uses JavaScript to describe styles in a hassle-free, declarative, and reusable manner that is compiled in the browser, server-side, or at build time in the node.

What is React Styled-Components?

As already mentioned, styled components is a library created for React and React Native developers, enabling them to use component-level styles in their applications. Styled-components are a combination of JavaScript and CSS using the CSS-in-JS technique.

CSS offers developers the flexibility to reuse their codes of a particular project for another one. This is possible because styled-components are centered on tagged template literals, which means the CSS codes are written between backticks while styling your components. Another plus of styled-components is that they do not require the mapping of the already created components to external CSS styles.

More about Styled-Components:

Styled-components we’re created with the same operation as CSS modules. This way the scope of CSS is limited to a single component and will be inaccessible by any other element in the page or even component.

Say, you need to do styling in Box.js file. Following are the steps to follow:

  1. Install styled-components library by running npm install styled-components –save.
  2. Import a styled-component library into your component by writing import styled from ‘styled-components’;.
  3. Create a variable by choosing an HTML element where style keys are stored.
  4. Use the name of the created variable as a wrapper around the JSX elements.

The above steps can be summarised in a code format. In the cod format, styled objects from styled components that use tagged template literals for styling. A variable is then created to hold the styling and to act as a wrapper around the content. For this, we have <Box> and <Content> tags, to assign styled objects plus the HTML element for styling followed by the accompanying styles for the HTML element. The JSX or content in between them as tags are wrapped to use the variables created for styling.

import React from ‘react’;

import styled from ‘styled-components;

const Box = styled.div`

  margin: 40px;

  border: 5px black;

`;

const Content = styled.p`

  font-size: 16px;

  text-align: center;

`;

const Box = () => (

  <Box>

    <Content> Styling React Components </Content>

  </Box>

);

export default Box; thank 

What are the advantages of styled-components?

  • Provide unique class names for your styles thereby minimizing class name issues like name duplications, misspellings, and overlaps.
  • Easy identification of CSS that are applied and easy deletion of unused component styles as styling is connected to a specific component.
  • Simple and smart styling enabled through supported props and global themes, thereby nullifying the requirement of manually managing the chunks of classes.
  • Irrespective of the size of your codebase, you can import different styles into other project areas.

Endnote: Why is the styled-component in React important?

  • The consistency makes a styled-component easy for publishing a React component to NPM. Without clashing with CDS selectors, the components can be personalised through props and/or extending through styled(Component).
  • Without installing SASS or any extra build tools, you can get SASs trademark syntax out-of-the-box.
  • In React, to dynamically change styles or tweak the style in the way you want, you can make use of props.
  • With ThemeContext, you can get a theme object accessible to any of your components, and by default can be inserted into styled definitions.

Need more reasons to like React styled-components? Our experts are within your reach! Try Webdura!

Categories
TEKNOLOGI Utveckling

React Styled-Components: En genomgång

Hur bra är stålkomponenter i React för styling av webbsidor? Om du frågar oss skulle vi säga att det är ganska bra!

Att lägga till stil på webbsidor med hjälp av formaterade komponenter har varit den praxis som ger applikationer det typiska utseendet.

Så vad sägs om att vi lär oss lite om hur du stylar dina appar? Låt oss börja!

Vilka är förutsättningarna?

Har du följande förutsättningar installerad och igång för att följa kodning delen?

  • Kommandoradsgränssnitt körs på administrativa behörigheter
  • JavaScript och CSS-förståelse
  • Garn- eller npm-pakethanterare 
  • som VS-kod efter eget val
  • Den senaste versionen av Node.JS

Vad är React och dess komponenter?

React är ett JavaScript-bibliotek med öppen källkod som drivs av Facebook Inc. Om du ser fram emot att bygga en app i ett urbant och lyhört användargränssnitt och komponenter, då är React din bästa handling. React är ett av de mest föredragna ramverken för frontend-utvecklare eftersom det är komponentbaserat.

React i front-end integrerar väl med backend-bibliotek som Node.JS, Django, Java bland andra. Som ett snabbt, enkelt och skalbart ramverk utökar React data ändringar i dina applikationer utan att behöva ladda om applikationerna.

Applikationer byggda med React har möjlighet att utveckla var och en av dess delar separat och kan återanvändas som en komponent. React-komponenter är återanvändbara JavaScript-funktioner som hanterar vad som visas på användargränssnittet och i vilken sekvens det visas. React-komponenterna returnerar HTML-skript och andra delar byggda separat som JSX-kod genom render()-funktionen.

Dessa komponenter samlas sedan ihop för att skapa komplexa användargränssnitt. Dessutom gör React-komponenterna det möjligt för utvecklare att segmentera applikationens användargränssnitt i oberoende och återanvändbara sektioner för att engagera varje sektion i segregering.

Delarna i en webbapplikation som navigeringsfält, sökfält, rubrik och andra sektioner byggs som komponenter och slås samman till ett enda användargränssnitt med hjälp av React-komponenter. Komponenterna i React kan skrivas som funktioner eller klasser. Funktioner eller klasser accepterar definierade input/props för att fixa vad som ska levereras på webbläsarna.

Rekvisita är som funktionsargument som skickar data som indata från en komponent till den andra. I JavaScript tar den funktionella komponenten in enstaka rekvisita som ett argument som överförs till en komponent och returnerar ett react-element utan att använda metoden render().

När det gäller klass komponenter, baskomponenter- React. Komponent – ​​returnera alla definierade React-element genom metoden react().

I React är knappar, innehållsområden, navigering, dialogrutor etc. några av frontend-delarna som kan definieras som komponenter. Låt oss nu se mer om Reacts stilade komponenter.

Stora styling strategier i Reactsägs

Vadom att nu diskutera de mest populära moderna styling strategierna i React och hur man använder dem för att styla dina React-komponenter? Här är några av de bästa styling strategierna i React:

 

  • CSS- och SCSS-stilmallar

 

Separata stilmallar är som det traditionella sättet att styla HTML-webbplatser med CSS eller CSS-förprocessor-SCSS.

 

  • CSS-moduler

 

CSS-moduler är CSS-filer där alla klassnamn tillsammans med animationsnamn är definierade i den lokala inställningen som standard.

 

  • Stiliserade komponenter

 

Styled-components är ett bibliotek skapat för React och React Native-utvecklare, vilket gör att de kan använda stilar på komponentnivå i sina applikationer. Stilade komponenter är en kombination av JavaScript och CSS som använder CSS-in-JS-tekniken.

 

  • JSS

 

JSS är ett författarverktyg för CSS som använder JavaScript för att beskriva stilar på ett problemfritt, deklarativt och återanvändbart sätt som kompileras i webbläsaren, på serversidan eller vid byggtid i noden.

Vad är React Style-Components?

Som redan nämnts är stilade komponenter ett bibliotek skapat för React och React Native-utvecklare, vilket gör att de kan använda stilar på komponentnivå i sina applikationer. Stilade komponenter är en kombination av JavaScript och CSS som använder CSS-in-JS-tekniken.

CSS erbjuder utvecklare flexibiliteten att återanvända sina koder för ett visst projekt för ett annat. Detta är möjligt eftersom formaterade komponenter är centrerade på taggade malllitterals, vilket innebär att CSS-koderna skrivs mellan backticks medan du stylar dina komponenter. Ett annat plus med formaterade komponenter är att de inte kräver mappning av de redan skapade komponenterna till externa CSS-stilar.

Mer om Styled-Components:

Styled-components vi skapade med samma funktion som CSS-moduler. På så sätt begränsas omfattningen av CSS till en enskild komponent och kommer att vara oåtkomlig för något annat element på sidan eller till och med komponent.

Säg att du måste göra styling i filen Box.js. Följande är stegen att följa:

  1. Installera styled-components- biblioteket genom att köra npm install styled-components –save.
  2. Importera ett bibliotek med formaterade komponenter till din komponent genom att skriva importformat från “formaterade komponenter”;.
  3. Skapa en variabel genom att välja ett HTML-element där stilnycklar lagras.
  4. Använd namnet på den skapade variabeln som ett omslag runt JSX-elementen.

Ovanstående steg kan sammanfattas i ett kodformat. I cod-formatet, formaterade objekt från formaterade komponenter som använder taggade malllitterals för styling. En variabel skapas sedan för att hålla stylingen och fungera som ett omslag runt innehållet. För detta har vi <Box> och <Content> taggar, för att tilldela formaterade objekt plus HTML-elementet för styling följt av de medföljande stilarna för HTML-elementet. JSX eller innehåll mellan dem som taggar lindas för att använda variablerna som skapats för styling.

importera Reagera från ‘reagera’;

importera stil från ‘stilade komponenter;

const Box = styled.div`

  margin: 40px;

  kant: 5px svart;

`;

const Innehåll = styled.p`

  font-size: 16px;

  text-align: center;

`;

konst Låda = () => (

  <Box>

    <Content> Styling React Components </Content>

  </Box>

);

exportera standardbox; tack 

Vilka är fördelarna med stylade komponenter?

  • Ange unika klassnamn för dina stilar och minimera därmed klassnamn problem som namn dubbletter, felstavningar och överlappningar.
  • Enkel identifiering av CSS som tillämpas och enkel radering av oanvända komponent stilar eftersom styling är kopplat till en specifik komponent.
  • Enkel och smart styling som möjliggörs genom stödda rekvisita och globala teman, vilket upphäver kravet på att manuellt hantera delar av klasser.
  • Oavsett storleken på din kodbas kan du importera olika stilar till andra projektområden.

Slutnot: Varför är den stilade komponenten i React viktig?

  • Konsistensen gör det enkelt att publicera en React-komponent till NPM med en formaterad komponent. Utan att krocka med CDS-väljare, kan komponenterna anpassas med hjälp av rekvisita och/eller förlängas genom styled(Component).
  • Utan att installera SASS eller några extra byggverktyg kan du få SAS varumärkes syntax direkt.
  • I React, för att dynamiskt ändra stilar eller justera stilen på det sätt du vill, kan du använda rekvisita.
  • Med Theme Context kan du få ett tema objekt tillgängligt för alla dina komponenter, och som standard kan det infogas i stiliserade definitioner.

Behöver du fler anledningar att gilla React-stilade komponenter? Våra experter finns inom räckhåll! Prova Webdura!

 

Categories
DEVELOPMENT TECHNOLOGY

10 ways to improve the software QA process

A product is ready in the dev environment. But would that be enough to roll it out to your customers? Definitely NO! 

Testing is the most important activity for ensuring that the product developed is in line with business expectations. As an integral part of the software development process, testing helps you evaluate the overall product quality, stability, usability, and security. 

Wouldn’t it be great to have a reference guide to verify whether your QA processes are aligned with the radical ways of QA practices? So this is what we are trying to convey through this blog. Let’s begin…

QA planning and processes

QA plan and the process should be well defined and documented. A person from your team or any stakeholder should comprehend and get the hang of the overall testing strategy and the business goals. 

Good documentation fills the gap between the team and the project stakeholders. So proper planning and defined process will bring quality to how the project meets customers’ needs and requirements. *

For this, we need a quality management plan to support project stakeholders and entail the benchmarked quality standards. The plan should cover quality objectives, activities, tools, and reporting defects and problems. 

Test strategy is a more detailed document that should align with the requirements. It should cover the scope of testing, test objectives, test schedule, defect tracking, and risks identified. 

Test plan to prioritize and describe the testing scope and activities. It should be brief and contain only appropriate information to avoid duplication and effort. Test cases should be unique and clear to classify, track and review at later stages.

Test-oriented implementation

Test-oriented implementation is one of the best ways to improve the quality of the software. One of the ways to achieve this is by using extreme programming (XP). XP is a software development methodology that focuses on developing high-quality software with the capability to adapt to changing requirements. 

2 XP practices are closely related to testing:

  1. Test-driven development
  2. Pair programming

Test-driven development (TDD)

In Test-driven development, the developer writes the test cases first and then writes the code. When a new feature or an enhancement comes, the developer starts with writing a test. An automated test case will be written before writing the code to fulfill that test. This method will help to improve the design and refactor the code till it passes all the tests merely focusing on the functionality. 

TDD is an iterative development method that will help to increase productivity and quality of the code and application. Benefits of TDD:

  1. Increase quality
  2. Reduce development costs
  3. Reduce coding complexity 
  4. High productivity 

Pair programming

Pair programming can also be called an extreme programming technique. 2 developers will be working in parallel on the same computer. One will write the code and the other will review the code and provide suggestions. This can increase code quality thus reduce debugging and refactoring costs. 

Benefits of Pair programming:

  1. High code quality
  2. More knowledge on the product and how it works 
  3. Clean code

Start testing early

Plan a testing strategy early rather than pushing it to the end of the development. This can reduce unidentified defects, implicit requirements, and gaps. 

Frequent testing can also help to get continuous feedback from the business and stakeholders. This will help to increase the quality and stability of the product.

Automation- this can help to increase test coverage and improve the testing process. 

Team collaboration and agile ways of working help to build cross-functional teams where members will be tightly coupled thus increasing productivity and quality.

Regulate technical reviews often

Frequent Technical reviews by peers to identify and track functional and technical defects at the early stages. Formal Technical review (FTR) is a round table meeting where software engineers ensure that the developed software meets the predefined standards and requirements. 

The best time to do FTR is when the MVP is in place or when it is matured enough to assess. After the review, a detailed report should be prepared to analyze the product or how good it is to release to the market. 

UAT

End-user testing or UAT is mainly done by Product owners (PO) and Business analysts to measure and review the deliverables. Check the gaps, whether the product developed is in line with the requirements, and ensure the quality is met.

UAT is mainly done to check whether the product is ready for release to market. UAT helps to identify defects/ gaps missed during the unit and integration testing. Sometimes the QA misses or if there is a gap in the knowledge of the product then the POs will be able to identify during UAT.

A good test case or test user documentation will help to do a smooth UAT and the internal stakeholders will be able to mark and track the errors rectified and which all are pending to fix.

Increase automation tests

Automation tests using automation tools can considerably improve the quality of the software and also reduce the time to run the tests. Automation can help when you are planning to do:

  1. Cross-device and cross-browser testing
  2. Regression
  3. Performance testing
  4. Load testing

Automation saves time, reduces human errors, enhances test coverage, and helps in batch testing and parallel execution.

Continuous Integration (CI) and Continuous Delivery (CD)

CI helps to integrate the changes and enhancements into a product multiple times in a day. Each piece of code runs the integration tests whenever a change is made. This will detect defects and bugs quickly and also find them in the code very easily. A very good practice is to combine the CI with automation.

CD is mainly practiced for Agile methodology where you can release the changes to the customers quickly. With CD, you can automatically deploy the changes that pass the tests.

CI/CD requires continuous testing with the help of automation in a single system.

Exploratory and Ad hoc testing

It is like you are examining your product with no predefined test strategy or test cases. Exploratory testing is conducted on a fly without any plan or test design and it is executed quickly. Then the results are

Categories
TEKNOLOGI Utveckling

10 sätt att förbättra programvarans QA-process

En produkt är klar i utvecklar miljön. Men skulle det räcka för att rulla ut det till dina kunder? Definitivt inte! 

Testning är den viktigaste aktiviteten för att säkerställa att den produkt som utvecklats är i linje med verksamhetens förväntningar. Som en integrerad del av mjukvaruutveckling processen hjälper testning dig att utvärdera den övergripande produktkvaliteten, stabiliteten, användbarheten och säkerheten. 

Skulle det inte vara bra att ha en referensguide för att verifiera om dina QA-processer är i linje med de radikala sätten för QA-praxis? Så detta är vad vi försöker förmedla genom denna blogg. Låt oss börja…

QA planering och processer

QA plan och processen bör vara väl definierade och dokumenterade. En person från ditt team eller någon annan intressent bör förstå och få kläm på den övergripande teststrategier och affärsmålen. 

Bra dokumentation fyller gapet mellan teamet och projektets intressenter. Så korrekt planering och definierad process kommer att ge kvalitet till hur projektet möter kundernas behov och krav. *

För detta behöver vi en kvalitetsstyrnings plan för att stödja projektets intressenter och innebära riktmärkta kvalitetsstandarder. Planen bör omfatta kvalitetsmål, aktiviteter, verktyg och rapportering av brister och problem. 

Teststrategi är ett mer detaljerat dokument som bör överensstämma med kraven. Den bör täcka omfattningen av testning, testmål, testschema, defekt spårning och identifierade risker. 

Testplan för att prioritera och beskriva testningens omfattning och aktiviteter. Den bör vara kortfattad och endast innehålla lämplig information för att undvika dubbelarbete och ansträngning. Testfall bör vara unika och tydliga att klassificera, spåra och granska i senare skeden.

Textorienterad implementering

Textorienterad implementering är ett av de bästa sätten att förbättra kvaliteten på programvaran. Ett av sätten att uppnå detta är genom att använda extreme programming (XP). XP är en metod för mjukvaruutveckling som fokuserar på att utveckla högkvalitativ programvara med förmågan att anpassa sig till förändrade krav. 

2 XP-praxis är nära relaterade till testning:

  1. Testdriven utveckling
  2. Parprogrammering

Testdriven utveckling (TDD)

I testdriven utveckling skriver utvecklaren testfallen först och sedan koden. När en ny funktion eller en förbättring kommer, börjar utvecklaren med att skriva ett test. Ett automatiserat testfall kommer att skrivas innan du skriver koden för att uppfylla det testet. Denna metod kommer att hjälpa till att förbättra designen och refaktorisera koden tills den klarar alla tester och bara fokusera på funktionaliteten. 

TDD är en iterativ utvecklingsmodell som hjälper till att öka produktiviteten och kvaliteten på koden och applikationen. Fördelar med TDD:

  1. Öka kvaliteten
  2. Minska utvecklingskostnaderna
  3. Minska kodning komplexiteten 
  4. Hög produktivitet 

Parprogrammering

Parprogrammering kan också kallas en extrem programmeringsteknik. 2 utvecklare kommer att arbeta parallellt på samma dator. En kommer att skriva koden och den andra kommer att granska koden och ge förslag. Detta kan öka kod kvaliteten och därmed minska kostnaderna för felsökning och om faktorer. 

Fördelar med parprogrammering:

  1. Hög kodkvalitet
  2. Mer kunskap om produkten och hur den fungerar 
  3. Ren kod

Börja testa tidigt

Planera en teststrategi tidigt istället för att driva den till slutet av utvecklingen. Detta kan minska oidentifierade defekter, implicita krav och luckor. 

Frekventa tester kan också hjälpa till att få kontinuerlig feedback från verksamheten och intressenter. Detta kommer att bidra till att öka kvaliteten och stabiliteten hos produkten.

Automation – detta kan hjälpa till att öka testa täckningen och förbättra testprocessen. 

Teamsamarbete och agila arbetssätt hjälper till att bygga tvärfunktionella team där medlemmarna kommer att vara tätt kopplade och därmed öka produktiviteten och kvaliteten.

Reglera tekniska granskningar ofta

Frekventa tekniska granskningar av kollegor för att identifiera och spåra funktionella och tekniska defekter i tidiga skeden. Formal Technical Review (FTR) är ett rundabordsmöte där mjukvaruingenjörer säkerställer att den utvecklade mjukvaran uppfyller de fördefinierade standarderna och kraven. 

Den bästa tiden att göra FTR är när MVP är på plats eller när den är mogen nog att bedöma. Efter granskningen bör en detaljerad rapport utarbetas för att analysera produkten eller hur bra den är att släppa ut på marknaden. 

UAT

Slutanvändartestning eller UAT görs huvudsakligen av produktägare (PO) och affärsanalytiker för att mäta och granska leveranserna. Kontrollera luckorna, om den utvecklade produkten är i linje med kraven och se till att kvaliteten är uppfylld.

UAT görs främst för att kontrollera om produkten är redo att släppas på marknaden. UAT hjälper till att identifiera defekter/luckor som missas under enheten och integrationstestning. Ibland missar QA eller om det finns en lucka i kunskapen om produkten så kommer POs att kunna identifiera under UAT.

Ett bra testfall eller test användardokumentation hjälper till att göra en smidig UAT och de interna intressenterna kommer att kunna markera och spåra de fel som åtgärdats och som alla väntar på att fixa.

Öka automationstester

Automatiseringstester med hjälp av automationsverktyg kan avsevärt förbättra kvaliteten på programvaran och även minska tiden för att köra testerna. Automation kan hjälpa till när du planerar att göra:

  1. Cross-enhet och olika webbläsare testning
  2. Regression
  3. prestandatester
  4. lasttest

Automation sparar tid, minskar mänskliga fel, förbättrar testtäckning, och hjälper till att batch testning och parallell exekvering.

Continuous Integration (CI) och Continuous Delivery (CD)

CI hjälper till att integrera ändringarna och förbättringarna i en produkt flera gånger på en dag. Varje kodbit kör integrationstesten närhelst en ändring görs. Detta kommer att upptäcka defekter och buggar snabbt och även hitta dem i koden mycket enkelt. En mycket bra praxis är att kombinera CI med automatisering.

CD praktiseras främst för Agile metodik där du snabbt kan släppa ändringarna till kunderna. Med CD kan du automatiskt distribuera ändringarna som klarar testerna.

CI/CD kräver kontinuerlig testning med hjälp av automatisering i ett enda system.

Utforskande och ad hoc-tester

Det är som att du undersöker din produkt utan fördefinierad teststrategi eller testfall. Utforskande testning utförs på en fluga utan någon plan eller testdesign och den utförs snabbt. Då är resultaten

 

Categories
DEVELOPMENT TECHNOLOGY

A guide for unit testing React using Jest and Enzyme

Want to avoid legacy codes? Any codes that are not tested are classified as legacy codes. To avoid legacy codes, what can you do? The solution is quite simple- use test-driven development (TDD)!

There are many tools for testing JavaScript and React.JS framework, we are narrowing down our discussion to unit testing React using Jest and Enzyme.

What is unit testing and why is it significant?

Unit testing is an integral part of the software development process for assuring product stability. Through unit testing, you can be sure that all the components of your product are tested and ready to be live.

Why is unit testing significant in the software development process? It can:

  • Improve the quality of code
  • Quickly identify the future breaks in an always changing software requirements
  • Bugs can be found at an early stage, and hence the cost of fixing bugs can be reduced

How is Jest similar to Enzyme?

Jest and Enzyme are resilient tools for testing React User Interfaces. These help in making sure that your React app has a user interface that is complying to the set requirements. Jest and Enzyme are developed and installed using Node Pack Manager. It has a large supporting community for finding your way out during any stagnation point during the app development process.

How is Jest different from Enzyme?

The purpose served by Jest and Enzyme is slightly different from each other. 

Jest is a complete feature-rich test framework. Jest can run test scripts on all your tests and the whole assertion library. Jest works well not only with React, but also with other frameworks. A JavaScript-based web application will use NodeJS to build the server, Jest allows you to run tests for your whole application with one test library.

Enzyme instead of serving a full testing library, it acts as the library that makes testing React components even easier. Enzyme can be integrated with different test libraries including Jest. 

If you are developing a React app, it will make more sense to use bothe Jest and Enzyme together for automated UI testing.

Unit testing React.JS apps using Jest and Enzyme: A step-by-step approach

Jest is a JavaScript testing framework centered on simplicity, that works on ultramodern framework and using pure JavaScript. Enzyme is used for testing React.JS components, and is a very easy-to-use and intuitive library.

Here is the step-by-step procedure for testing React app using Jest and Enzyme:

Installation

  1. Start installing all the necessary libraries
  2. Open the application and console using yarn or npm for installing Jest, Enzyme, and other required plugins
  3. Apps created using create-react-app does not need to install Jest because it is already inbuilt
  4. If there is no pre-installed Jest, you can use yarn add jest command
  5. Finally, open the application code and set up the testing environment

Fixing test file

  1. Open the setupTest.js file and configure the adapter to use Jest in the test environment properly
  2. Once it is ready and saved, start considering test cases

Setting up test cases

  1. Understand what is happening inside while testing an app and be sure of the cases that are very crucial for us to test. Make sure that all the components in the app are rendering
  2. Verify whether the props passed through the components are correct
  3. To check the logic, make sure that while clicking the buttons, the values change on both accounts
  4. Finally test snapshots 

Now we have four more main groups to test and are briefed below

Components rendering check

  1. Test whether your components in the first group are rendered correctly and group those using describe
  2. Open the App.test.js file and pull all the tests. Bigger applications need to be put into different files and if the bigger applications have two components, it is ideal to create a test file for each of them separately.
  3. Using shallow, make sure that components are rendering without children. If there is an additional element rendered in the component, define that element and use the .contain () method to see if it is present.
  4. Using the userBalance object can helpb with moicks for the props that are used for the next step.

Passing props testing

  1. Now pass the props to the components
  2. Create another group with describe ()
  3. Inside the group, set tests to check if the props are accepted, displayed correctly and notification props are passed as well
  4. Make sure the props are passed to child components successfully
  5. Test the logic of your application right now

Logic testing

  1. Logic can be complicated as an important functionality like changing account values  on button click event is involved
  2. Add another describe () group in the App.test.js
  3. Use .simulate () method to simulate the click event on the selected button
  4. Run tests to check functionality after a click event

Snapshots

  1. Use additional plugin that was installed at the beginning enzyme-to-json
  2. Define cases for App component, AccountBalance and Notification component
  3. If there is an update in the UI, and the snapshot tests fail, you can use u to update the snapshots
  4. Firstly done snapshots, new folders in your app called  __snapshots__ where it will be saved

Testing

  1. Run the tests and test your application
  2. Open the terminal and run the command yarn test or npm test
  3. Make sure the tests are running and you will have the list of tests that passed and can see the tests to understand how the tests to see how it looks when it fails

Conclusion

With robust test frameworks like  Jets and Enzyme, your React App becomes more stable and enhances the quality of your code. It helps developers in fixing bugs faster. For complicated applications, these test frameworks will ensure that their codes work the way that it was expected, and QA engineers can reduce their efforts for  UI regressions.

The betterment of your software is ensured by using tools like Jest and Enzyme. When the projects get more complex, right tools like Jest and Enzyme can help you with managing that complexity.

Categories
TEKNOLOGI Utveckling

En guide för enhetstestning React using Jest and Enzyme

Vill du undvika äldre koder? Alla koder som inte är testade klassificeras som äldre koder. Vad kan du göra för att undvika äldre koder? Lösningen är ganska enkel – använd testdriven utveckling (TDD)!

Det finns många verktyg för att testa JavaScript och React.JS-ramverket, vi begränsar vår diskussion till enhetstestning av React med hjälp av Jest och Enzyme.

Vad är enhetstestning och varför är det viktigt?

Enhetstestning är en integrerad del av mjukvaruutveckling processen för att säkerställa produkt stabilitet. Genom enhetstestning kan du vara säker på att alla komponenter i din produkt är testade och redo att användas.

Varför är enhetstestning viktig i mjukvaruutvecklingsprocessen? Det kan:

  • Förbättra kodens kvalitet
  • Snabbt identifiera framtida avbrott i ett ständigt föränderligt programvarukrav
  • Buggar kan hittas i ett tidigt skede, och därmed kan kostnaden för att fixa buggar minskas.

Hur liknar Jest Enzyme?

Jest och Enzyme är motståndskraftiga verktyg för att testa React User Interfaces. Dessa hjälper till att se till att din React-app har ett användargränssnitt som uppfyller de uppställda kraven. Jest och Enzyme utvecklas och installeras med Node Pack Manager. Den har en stor stödjande gemenskap för att hitta din väg ut under en stagnationspunkt under apputvecklingsprocessen.

Hur skiljer sig Jest från Enzyme?

Syftet med Jest och Enzyme skiljer sig något från varandra. 

Jest är ett komplett funktionsrikt testramverk. Jest kan köra testskript på alla dina tester och hela påståendebiblioteket. Jest fungerar bra inte bara med React, utan även med andra ramverk. En JavaScript-baserad webbapplikation kommer att använda Node JS för att bygga servern, Jest låter dig köra tester för hela din applikation med ett testbibliotek.

Enzym istället för att tjäna ett komplett testbibliotek, fungerar det som biblioteket som gör testning av React-komponenter ännu enklare. Enzym kan integreras med olika testbibliotek inklusive Jest. 

Om du utvecklar en React-app är det mer vettigt att använda både Jest och Enzyme tillsammans för automatiserad UI-testing.

Enhetstestning av React.JS-appar med hjälp av Jest och Enzyme: En steg-för-steg-strategi

Jest är ett JavaScript-testramverk centrerat på enkelhet, som fungerar på ett ultramodernt ramverk och med rent JavaScript. Enzyme används för att testa React.JS-komponenter och är ett mycket lättanvänt och intuitivt bibliotek.

Här är steg-för-steg-proceduren för att testa React-appen med Jest och Enzyme:

Installation

  1. Börja installera alla nödvändiga bibliotek
  2. Öppna applikationen och konsolen med yarn eller npm för att installera Jest, Enzyme och andra nödvändiga plugins
  3. Appar skapade med create-react -appen behöver inte installera Jest eftersom den redan är inbyggd
  4. Om det inte finns någon förinstallerad Jest kan du använda yarn add jest kommandotÖppna
  5. slutligen applikationskoden och ställ in testmiljön

Fixa

  1. testfil Öppna setupTest.js filen och konfigurera adaptern för att använda Jest i testmiljön på rätt sätt
  2. När den är klar och sparad, börja överväga testfall

Konfigurera testfall

  1. Förstå vad som händer inuti medan du testar en app och vara säker på de fall som är mycket avgörande för oss att testa . Se till att alla komponenter i appen återges.
  2. Verifiera om rekvisita som passerat genom komponenterna är korrekta
  3. För att kontrollera logiken, se till att när du klickar på knapparna ändras värdena på båda kontona. Testa
  4. slutligen ögonblicksbilder 

Nu har vi fyra huvudgrupper till att testa och informerade under

Components rendering check

  1. testa om dina komponenter i den första gruppen återges korrekt och grupp som använder beskriva
  2. Öppna App.test.js filen och dra alla tester. Större applikationer måste läggas in i olika filer och om de större applikationerna har två komponenter är det idealiskt att skapa en testfil för var och en av dem separat.
  3. Använd grunt, se till att komponenterna återges utan barn. Om det finns ytterligare ett element i komponenten, definiera det elementet och använd metoden .contain () för att se om det finns.
  4. Att använda userBalance- objektet kan hjälpa till med moicks för rekvisita som används för nästa steg.

Godkänd rekvisitatestning Skicka

  1. nu rekvisitan till komponenterna
  2. Skapa en annan grupp med beskriv ()
  3. Inuti gruppen, ställ in tester för att kontrollera om rekvisitan accepteras, visas korrekt och meddelanderekvisita också har godkänts.
  4. Se till att rekvisitan skickas till underordnade komponenter framgångsrikt
  5. Testa logiken i din applikation just nu

Logiktestning

  1. Logik kan vara komplicerad eftersom en viktig funktionalitet som att ändraär inblandad
  2. Lägg till ytterligare en () kontovärden på enbeskriv-grupp i App.test.js
  3. knappklickshändelseAnvänd .simulate ()-metoden för att simulera klicka på händelsen på den valda knappen
  4. Kör tester för att kontrollera funktionaliteten efter en klickhändelse

Ögonblicksbilder

  1. Använd ytterligare plugin som installerades i början enzym-to-json
  2. Definiera fall för App-komponent, AccountBalance och Notification-komponent
  3. Om det finns en uppdatering i användargränssnittet, och ögonblicksbildstesten misslyckas, du kan använda u för att uppdatera ögonblicksbilderna.
  4. Först gjorda ögonblicksbilder, nya mappar i din app som heter  __snapshots__ där det kommer att sparas

Testing

  1. Ru n de tester och testa din ansökan
  2. Öppna terminalen och körkommandot garntest eller NPM prov
  3. se till att testerna körs och du kommer att ha en lista av tester som passerade och kan se tester för att förstå hur de tester för att se hur det ser ut när den misslyckas

Slutsats

Med robusta testramverk som Jets och Enzyme blir din React-app mer stabil och förbättrar kvaliteten på din kod. Det hjälper utvecklare att fixa buggar snabbare. För komplicerade applikationer kommer dessa testramverk att säkerställa att deras koder fungerar som de förväntades, och QA-ingenjörer kan minska sina ansträngningar för UI-regressioner.

Förbättringen av din programvara säkerställs genom att använda verktyg som Jest och Enzyme. När projekten blir mer komplexa kan rätt verktyg som Jest och Enzyme hjälpa dig att hantera den komplexiteten.