Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

State Management with Svelte - Context API (Part 2)

Disclaimer - If you are unfamiliar with props in Svelte applications, then please read this blog post before proceeding on. You must understand the limitations of props to better understand the Context API and how it addresses those limitations. For components that need to share data to lower-level descendant components (and slotted content) within the same subtree, the Context API offers two methods for these components to communicate data without prop drilling or dispatching events: getContext and setContext . When a component calls setContext , the component defines a context , which is a value (primitive or object) representing data that can only be accessed by the component's descendants via the getContext method. Defining a context with setContext requires the component to supply a context key and a value . The context key helps to retrieve the context value from the closest ancestor component with a defined context corresponding to this key. For a descendant component to consume context defined within one of its ancestors, call the getContext method, passing to it the context key. Note : The context key does not have to be a string; it can be any value. Using a string as the context key has the downside of conflicting with other contexts with the same context key, especially if these contexts belong to third-party libraries that you have little to no control over. Using an object literal as the context key ensures that its context won't conflict with other contexts since object literals are compared via referential equality. Both setContext and getContext must be called during component initialization at the top-level of <script /> , similar to lifecycle methods. Let's revisit the <Grandparent /> , <Parent /> and <Child /> components' example and refactor the code by substituting the props with context. ( Grandparent.svelte ) ( Parent.svelte ) ( Child.svelte ) This approach is much cleaner compared to the props approach. The intermediate <Parent /> component no longer contains any reference to message , which it previously received from the <Grandparent /> component and forwarded it directly to the <Child /> component. Only the descendant components concerned with message (in this case, the <Child /> component) receive it. At a minimum, a simple scatterplot consists of two labeled axes (an x-axis and y-axis) and some dots. Optionally, a scatterplot may display a legend mapping a dot's color to a specific category it belongs to (for classification purposes). If you break down a <Scatterplot /> component into its constituent components, then you might arrive at this component hierarchy: Note : <svg /> is commonly the root element of interactive data visualizations, especially those built using D3 . When you include props, then you may notice how reliant these components are on the same set of props. As the requirements of the visualization grow and more features are added, passing these props explicitly to each of these components becomes repetitive and unmaintainable. Visit this simple Svelte REPL demo to see how the Context API allows these child components to receive all of this data from a single, common parent component ( <Scatterplot /> ): Context API Demo - D3 Scatterplot The scatterplot shows the relationship between the petal length and petal width of flowers classified as species of Iris (Iris setosa, Iris virginica and Iris versicolor). If you have a background in a data science, statistics or machine learning background, then you are likely to have encountered and explored this multivariate dataset when learning introductory classification algorithms. ( App.svelte ) The <App /> component fetches the Iris dataset from a GitHub Gist, and it establishes the petal length as the independent variable ( x ) and petal width as the dependent variable ( y ) to be plotted in the scatterplot. Each data point is categorized as one of three flower species: setosa, versicolor and virginica. Once the data is fetched, the <Scatterplot /> component is rendered using this data and custom configuration options. Note : The <Scatterplot /> component can accept data from either a remote source (as shown above via d3.csv , fetch , etc.) or locally with this arrangement. The other props passed to the <Scatterplot /> component configure certain aspects of the scatterplot such as its dimensions and axes. ( context-keys.js ) To avoid any conflicts with other contexts, the context key for the scatterplot will be a literal object. This object will be referenced by all of the scatterplot's constituent components when they access the context set by the <Scatterplot /> component. ( Scatterplot.svelte ) The <Scatterplot /> component receives a set of props from a consuming component (in this case, <App /> ), and creates a context via setContext , which contains these values. Notice how no props are passed to the <Dots /> , <XAxis /> , <YAxis /> and <Legend /> components because each of these components will access those values directly from this context via getContext . ( Dots.svelte ) Since both axes are drawn dimensions.margins.left pixels away from the left-side of the visualization, we must automatically translate all of the dots horizontally by this same amount of pixels to ensure that they are drawn within the confines of these axes ( translate(${dimensions.margins.left}, 0) ). Then, each data point is drawn as a dot with a radius of three pixels, colored based on its flower species and positioned based on the values of xScale(item.x) and yScale(item.y) . ( XAxis.svelte ) ( YAxis.svelte ) To generate an axis' tick marks, call the ticks method on the scale function ( xScale or yScale ). The number of tick marks created is based on the number passed to the ticks method. To space the tick marks out evenly, translate each tick mark by a number of pixels determined by scale(tick) ( translate(${xScale(tick)} 0) for each x-axis tick mark and translate(0, ${yScale(tick)}) for each y-axis' tick mark). To position the labels ( <text /> element, last child of the outermost <g /> element), space them slightly away from the halfway point of its corresponding axis line ( <path class="axis-line" /> element). ( Legend.svelte ) The legend is placed 25 pixels to the right of the y-axis (adding x pixels to dimensions.margins.left for the horizontal translation ensures the legend is shifted x pixels from the y-axis) and 25 pixels from the top-side of the canvas. Each category is displayed with its unique color representation and label. If you have built React applications, then up to this point, Svelte's Context API may appear similar to React's Context API : sharing values between components of the same subtree without having to explicitly specify props at every level of the component hierarchy . In Svelte, the setContext creates the context, sets its value and automatically provides access to this context for all of the component's descendants. In React, you must first create the context with the createContext method. Note : According to React's documentation , providing a default value to createContext is useful for testing components in isolation without having to wrap them within a provider component. This value serves as a fallback for when a component has no matching provider (for example, <ScatterplotCtx.Provider /> ) above it. For components to access this context value, create a provider component and have it wrap all of these components: In React, updates to the provider component will cause the useContext hook to trigger a rerender using the latest context value passed to this provider component. However, in Svelte, descendant components cannot receive updates from a context whenever its set to a different value via a subsequent call to setContext . These components are only able to access the values made available to them from their ancestor component (the one setting the context) during component initialization. Since the components are not updated with the new context value and not re-rendered as a result of those changes, we cannot consider the Context API as reactive feature of Svelte. For reactivity, we must use props and/or stores , which allow components to access data and subscribe to updates from global data stores (not restricted to a subtree of components). Proceed to the next blog post to learn more about Svelte stores. If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial State Management with Svelte - Context API (Part 2)

State Management with Svelte - Props (Part 1)

Each component of a client-side application contains internal state that encapsulates its own data, which determines the component's behavior and stores business-related data for rendering. When composing many components into a multi-level hierarchy, components must communicate data and coordinate amongst each other to perform more complex tasks. For example, a <SearchBar /> component might pass a list of search results to a <TypeaheadDropdown /> component to display suggestions based on the currently typed query. There are three common approaches to facilitate communication amongst the various components within a Svelte application: Having full control over state within an application allows developers to know how data flows throughout the application, better reason about the data and optimize accordingly. Modeling data flow with props, contexts and/or stores improves the organization of state, normalizes data to reduce instances of duplicated data and curtails the amount of time spent on debugging (quickly identify the component/s or portions of state responsible for a bug). Below, and in two additional blog posts, I'm going to show you: The simplest form of communication involves a parent component passing data to its direct child component/s via props . This concept is widely adopted in other popular component-based libraries/frameworks, such as React and Vue . In Svelte, the export keyword defines a prop that a component can accept from its consumers. ( Parent.svelte ) ( Child.svelte ) With props, data flows unidirectionally downwards from a higher-level component to a lower-level component in the component hierarchy. This means changes made to a prop in a child component will not propagate back to its parent component and yield any unwanted side effects. Unlike two-way data-binding in AngularJS , which caused performance issues and modal updates to cascade, one-way data binding with props reduces the number of possible points of failure due to the predictable nature of component/application state. If multiple props need to passed to a component, then consider packing all the props into an object and spreading them onto the component, which serves as a convenient shortcut for passing many props rather than individually specifying them. ( Parent.svelte ) ( Child.svelte ) If the parent component does not specify the prop on the child component, then its value will be set to undefined by default. However, instead of setting its value to undefined , the prop can be set to a default initial value. ( Parent.svelte ) ( Child.svelte ) Specifying props in a component with export let allows those props to be modified within the component itself. ( Parent.svelte ) ( Child.svelte ) When clicking the button and incrementing the value of the prop count , the newly incremented value is logged to the developers tool console, which indicates this prop being modified in the <Child /> component. However, this change is not propagated to the <Parent /> component. The count displayed within its <p /> tag remains zero no matter how many times you click on the "Increment" button. Try it out here . Swapping let for const changes the behavior of export . Unlike variables declared with export let , variables declared with export const , export function or export class are not props, but instead, are readonly constants that can be imported into other components as named imports. ( Parent.svelte ) ( Child.svelte ) Try it out here . To export these variables for consumption in other components via an import statement, declare the <script /> block with the attribute context="module" , which will execute the code within the <script /> block once upon the evaluation of the module, not the instantiation of the component. Uncommenting out any of the count++ statements and then clicking on the button bound to the event handler containing this statement will result in an error being logged to the developers tool console and count not being incremented. Variables declared with export const cannot be reassigned to a different value. This also applies to variables declared with export function and export class . Note : Properties of an object declared with export const can be modified, but the reference to the object cannot be changed. Suppose you decide to export a function that changes a value within the component it is exported from. ( Parent.svelte ) ( Child.svelte ) Clicking the "Increment" button will call the imported incrementCount function. When incrementCount is executed, the value of count is incremented. Because count is declared within a <script context="module" /> block, count is not reactive, and therefore, the count value displayed within the <p /> tag remains zero. A function can be exported from an instance directly and accessed as a property on the component's reference, which can be obtained via the bind:this directive. These properties are accessible after the component has been mounted to the DOM. ( Parent.svelte ) ( Child.svelte ) When clicking the "Increment" button, not only is count incremented, but its new value is displayed in the <p /> . For grandchild components to receive data from grandparent components, that data must first be passed from the grandparent component to its child component (the grandchild's parent component), and then, that data must be passed from this parent component to its child component (the grandchild component). ( Grandparent.svelte ) ( Parent.svelte ) ( Child.svelte ) This process of explicitly and redundantly passing data from higher-level ancestor components to lower-level descendant components via props is known as prop drilling . As the number of component layers increases, it becomes more difficult to track these props, especially when refactoring components and having to manually rename or remove props. In the above example, if we decide to rename the message prop to greeting , then we would have to start renaming the prop at the <Grandparent /> component and traverse down its subtree, renaming the prop at each subsequent component (the <Parent /> and <Child /> components). Also, the intermediate <Parent /> component does not make use of the message prop whatsoever. It simply receives this prop and passes it directly to the <Child /> component. Having these types of props in our components can add unnecessary clutter to them and exacerbate our ability to understand and maintain these components. Alternatively, to make data available to a component and its descendants without prop drilling, Svelte provides the Context API . Proceed to the next blog post to learn more about Svelte's Context API. If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial State Management with Svelte - Props (Part 1)

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Vue 3 - The Composition API - Reusability (Part 2)

Vue's Options API constrains the reusability of logic across multiple components. Patterns involving mixins and higher-order components (HOCs) have been established to create reusable blocks of code and consolidate repeated state and functionality. However, each pattern has a drawback: With Vue 3's Composition API , component logic can be extracted, shared and reused amongst multiple components. Exposing Vue's core capabilities (reactivity and lifecycle hooks) as standalone, globally available functions allows developers to create custom hooks that are decoupled from any UI, but yet, can be consumed by any component. This can greatly improve the maintainability and flexibility of a large application composed of hundreds of components. Let's walkthrough an example demo to demonstrate the simplicity of writing reusable code with the Composition API. In this CodeSandbox demo , clicking the "Open Modal" button pops open a basic accessible modal that displays a list of links to sections in the official Vue.js documentation site. The <Modal /> component instance contains a setup option that houses all of its data, methods, lifecycle hooks, etc. ( src/components/Modal.vue ) Here's a brief overview of the code within the setup option: In a web application, a modal acts as a subordinate window to the browser window. Because modals can be used to communicate information to a user, they can be categorized as dialogs . Another component that behaves similarly to modals is toast notifications , which briefly notify users of certain events before disappearing. If you are not familiar with toast notifications, then have a look at an easy-to-use toast notifications library, toastr . Using the Composition API, we can implement a toast notification component that uses the same accessibility and closing logic as our modal component. Let's refactor this logic into a separate hook that can be used in both components. First, create a new directory, hooks , within the src directory. Then, create a new file useDialog.js within this new directory. Inside of src/hooks/useDialog.js , create a function called useDialog that declares a ref, isDialogOpened , and has two methods responsible for updating this ref's value, openDialog and closeDialog . To allow a component to access these functions and this ref, return them in an object. ( src/hooks/useDialog.js ) The useDialog function is created outside of the context of components as a standalone piece of functionality. Notice how this logic resembles the logic within the setup option of the <App /> component: Let's refactor this logic by replacing it with a call to the useDialog function. ( src/App.vue ) Since isDialogOpened is reactive, any updates to this value will be reflected wherever it is used in the component template. Examining at the <Modal /> component, we should extract out the methods and lifecycle hooks for re-use in a <ToastNotification /> component. Because the close method relies on the context object, the handleKeydown method relies on the modalRef ref and the onBeforeMount lifecycle hook relies on the prevRef ref, all of these values need to passed to the useDialog method when we migrate these methods and lifecycle hooks. ( src/hooks/useDialog.js ) Because the call to the useDialog function within the <App /> component does not need to pass prevRef , dialogRef (formerly modalRef ) and context , we should isolate this logic within a function initDialog , which will be exposed to the <Modal /> component and accept these arguments when called. ( src/hooks/useDialog.js ) We will also need to slightly adjust the <Modal /> component's template to call emitClose when the <button class="modal__close-btn" /> element is clicked. ( src/components/Modal.vue ) Because modalRef and prevRef are reactive, their updated values will be available to the methods and lifecycle hooks within useDialog whenever they are called. Try out these changes! When you click on the "Open Modal" button, the modal pops open, and focus is trapped within it. Once the modal is closed, the focus resumes back to the "Open Modal" button. Let's create a simple toast notification component. Add a new file to the src/components directory named ToastNotification.vue . Plug-in the same logic that is now used in the setup option of the <Modal /> component. ( src/components/ToastNotification.vue ) Let's add an example toast notification and a button that pops open this notification when clicked to the <App /> component. ( src/App.vue ) And with little effort (after the initial refactoring of functionality to useDialog ), we have successfully introduced a new component to our application. Additionally, these same steps can be repeated for other dialog-like components. If you would like to view the final version of this CodeSandbox demo, then click here . Composing and isolating functionality within a separate function makes it incredibly easy to integrate and share this logic amongst existing/new components. The Composition API's flexibility and compositional nature allows us to structure and group our logic based on high-level component features rather than low-level component details (in the case of the Options API). Try rewriting React functional components that use hooks with Vue 3's Composition API. If you want to learn more about Vue 3, then check out Fullstack Vue :

Thumbnail Image of Tutorial Vue 3 - The Composition API - Reusability (Part 2)

Vue 3 - The Composition API (Part 1)

As the most starred open source, JavaScript library/framework repository on GitHub, Vue.js has become a top three front-end technology alongside React.js and Angular in terms of popularity, usage, ecosystem activity and developer satisfaction. Compared to React.js and Angular, Vue.js is incrementally adoptable and provides a declarative API that resonates with AngularJS developers. Evan You , the author of Vue.js, explained the original concept of Vue.js as extracting the best parts of AngularJS, such as directives (i.e., v-if and v-show ), and building a lightweight, flexible alternative. Building large Vue.js applications requires composing components together with state management (i.e., Vuex ) and routing (i.e., Vue Router ) libraries. In September 2020, the Vue.js team officially released Vue 3, which welcomed a number of improvements and new features: Particularly, the Composition API of Vue 3 has been met with controversy due to its resemblance to React hooks and its philosophical divergence from the Options API , which emphasizes separation of concerns by defining component logic within specific options ( data , props , computed , methods , etc.). For those who prefer the Options API, unlike other major version upgrades that introduce incompatible changes, the Composition API will not break existing Vue components using Options API (" purely additive "). Although it offers similar logic composition capabilities as React hooks, the Composition API leverages Vue's reactivity system to circumvent several of React hooks' issues. To understand why the Composition API's new approach for creating components allows developers to better reason about and maintain large components, we will need to... A single file component consists of HTML-based markup ( <template /> ), CSS-based styles ( <style /> ) and JavaScript-based logic ( <script /> ), all self-contained within a single .vue file. Example : The following component will display "Hello World!" as red text. Note : The scoped attribute applies to CSS only to the elements within the current component. In the above example, the data function returns an object that represents the component's data. Vue converts each data property to a Proxy , which makes the state reactive by allowing for proper this bindings and tracking/triggering changes. The object returned by data contains a single property, greeting , which has a value of "Hello World!" and is rendered within the <p /> element's mustaches ( {{ ... }} ). For a one-time interpolation, use the v-once directive. Note : In previous versions of Vue, the reactivity system used Object.defineProperty , not Proxy . Now that you are familiar with the base structure of a component, let's explore a slightly more complex component. Open the CodeSandbox demo here . In this demo, let's look at a component that represents a simple accessible modal. When the modal is opened, the focus should be trapped within it. Elements within the modal should be "tabbable." When the modal is closed, the focus should return back to the element responsible for opening the modal. ( src/components/Modal.vue ) ( src/App.vue ) Here, the <Modal /> component is defined using the Options API , which organizes component logic into specific options. The initialization of internal state ( data ), the passed props ( props ), the emitted custom events ( emits ), the available instance methods ( methods ) and lifecycle hooks ( beforeMount , mounted and unmounted ) are clearly separated from one another. For an option to access values/methods defined within other options, those values/methods must be referenced via the this keyword, which refers to the component instance itself. Below is a list of commonly used options: Note : Do not use arrow functions when defining a watcher or methods / computed method. Otherwise, the this keyword will not reference the component instance. As a component grows larger with more new features, it increasingly becomes more difficult to maintain and reason about the component, especially when the logic of each feature is fragmented over the individual options. The RFC for the Composition API provides a side-by-side comparison of how logic related to a feature (also called a logical concern in the official documentation ) is distributed throughout a component's code. Each logical concern is identified by a unique color. Notice how neatly grouped each feature's logic is when using the Composition API. By restricting component logic to specific options, it adds a mental tax by requiring us to constantly switch from one block of code to another to understand/work on any single feature of a component. Also, it limits our ability to extract and reuse common logic between components. This is the primary motivation behind the Composition API. By exposing Vue's core capabilities, such as reactivity and lifecycle hooks, as standalone functions, the Composition API can use these functions within the setup component option, which is executed before the component is created (formerly the created lifecycle hook option) and serves as the component's main entry point. Let's revisit the simple accessible modal, but this time, create the component using the Composition API. Open the CodeSandbox demo here . ( src/components/Modal.vue ) ( src/App.vue ) All of the logic that was previously handled in multiple options of a Vue component is now contained within a single option, setup . Functions that behave similar to those options can be imported as named exports from vue and called anywhere within the setup function. For example, the lifecycle hook options beforeMount , mounted and unmounted can be replaced using the onBeforeMount , onMounted and onUnmounted methods in setup respectively. This allows component logic to be structured and arranged flexibly. The reactive data returned by the data option can be replaced using the ref and reactive methods in setup . The ref method accepts a default value and returns a reactive ref object that can be safely passed throughout the entire application. Because this object is mutable, the value can be directly modified. To reference this value, access this object's .value property. ref is commonly used for establishing reactivity for a single primitive value. To establish reactivity for an entire object, use the reactive method. setup exposes two arguments, props and context . props contains the props passed from a parent component. They are reactive and automatically updated whenever new props are passed in. To properly destructure props , which means still preserving each props reactivity after destructuring, use the toRefs method. context contains three properties: Within the context of the <Modal /> component: Although the component's methods are defined within the setup option, the component's template can only access these methods when they placed within the object returned by setup . This also applies to ref and reactive values, which are automatically unwrapped to allow the template to access their values without having to reference .value . The close method and modalRef ref are made available to the <Modal /> template. The close method is set to the @click shortcut directive, so when the user clicks this button, the "close" event will be emitted by the component, which will trigger the function set to @close on the <Modal /> component within the <App /> parent component (the closeModal method). When set to the <div class="model" /> element's ref , modalRef will reference this DOM element. A component built with the Composition API has its setup function only called once during its entire lifetime, regardless of how many times it is re-rendered. A React functional component using hooks is called whenever a re-render occurs as a result of a state/prop change, which pressures the browser's garbage collector. React provides useCallback to prevent inline functions in functional components from being garbage collected on subsequent re-renders via a referential equality check. Additionally, these re-renders may cause unnecessary re-renders, which happens when the function representing a child functional component is called when its parent component is re-rendered, even if it is completely stateless. Example : When the count increases/decreases upon clicking any one of the <Counter /> component's button, the Child function is called. However, its DOM is unaffected by this state change. This is an unnecessary re-render. If this component was larger with more inline handlers, calls to hooks, etc., then any unnecessary re-render would cause these inline handlers, etc. to be garbage collected. React provides a number of memoization-related methods ( useMemo , memo , etc.) to address this. Of course, you should use your browser's profiling tool first to identify your application's actual bottlenecks before chucking in useMemo , memo and other memoization techniques. Each developer reasons about code differently. Whether you find it easier to reason about code by its low-level (Options API, which is better suited for grouping logic by a low-level attributes of a component) or high-level (Composition API, which is better suited for grouping logic by a component's high-level features) implementation, you must always evaluate and make trade-offs that best serves your needs. You should definitely read this RFC that outlines the Vue team's rationale and decisions for the Composition API, along with addressing some of the common criticisms echoed within the Vue community. Many of these new features, such as portals and fragments, in Vue 3 are already present in React v16+. Try converting your React functional components to Vue 3 components using the Composition API. Please read Part 2 of this blog post to learn about the main benefit of the Composition API: the capability to extract and reuse shared logic . If you want to learn more about Vue 3, then check out Fullstack Vue :

Thumbnail Image of Tutorial Vue 3 - The Composition API (Part 1)

How to Write Your First Unit Test in React + TypeScript App

Tests make sure that changes in code don't break its functionality. For testing an app, we need a test runner. Create React App provides us a test runner called jest . Let's create a new app and inspect what it contains. The src directory contains all the app code and a file called App.test.tsx . This file contains a test that makes sure that the App component renders a link: Let's break it down and write our own tests to understand what's going on. Every test is a statement that claims something. In our case, test in App.test.tsx claims that the App component should render a “Learn React” link. This kind of statements consist of 3 stages: This is true for the test in the App.test.tsx , let's check: This is considered a good practice to structure tests in this way. Tests that comply the Arrange-Act-Assert structure are clean and easy to read. Let's start with a test for good ol' functions, and then come back to testing components. Testing functions is a bit easier to grasp and it will be much easier to apply this knowledge later, when testing components. Open App.tsx and add a new function: Now, open the App.test.tsx file and start testing this divide function. First of all, we need to describe what we want to test. For descriptions, jest has a describe function , which we can use like this: We can indent describe functions to create describe specific details about current tests we write: For actually running tests jest has it and test functions . We can use either of those, they do the same. The only difference is the name semantics: we can use it to construct test sentences more naturally. For example: Finally, let's actually write our first test! In the Assert stage we used a function called expect . It is also a jest global function . It returns an object with a bunch of useful methods to use. The full list of them we can find in the docs . In our case we use .toEqual method to check if the expect argument is equal to toEqual argument, i.e. if the expected result is equal to actual result. Now, it is time to check if our test is working, open the console and run: You will see that all the tests are passing: This is great! But we have to break our test 🤯 The immediately appearing thought is: “What would we do that?”. The reason is that we need to make sure that our test is working and that it tests the right thing . Let's look at the example: So, to test our test we're going to break it and see if it breaks with the correct intent. In this case we will see an error output: If we examine the reason why the test has failed, we will see that expected value is not equal to actual. This reason is valid, so the works correctly. Now let's try to test that divide function doesn't allow to divide by 0. We know that if we try to do that it will throw. To check functions that may throw we will use .toThrow method . Notice that we pass a () => divide(1, 0) here, this way jest knows that the occurred error is expected and there is no need to stop the testing itself. Again, let's test our test: The output will be: Thus, we know that our tests are correct. Later, we will use jest for writing tests for React component.

Thumbnail Image of Tutorial How to Write Your First Unit Test in React + TypeScript App