{"id":3264,"date":"2022-10-04T17:33:32","date_gmt":"2022-10-04T17:33:32","guid":{"rendered":"https:\/\/explore.techenutia.com\/?p=3264"},"modified":"2022-12-28T15:39:27","modified_gmt":"2022-12-28T15:39:27","slug":"unit-testing-in-react-introduction","status":"publish","type":"post","link":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/","title":{"rendered":"Unit Testing In React: Introduction"},"content":{"rendered":"\n<p>Unit testing is an important part of the Software development life cycle and unit tests are written and executed by developers in which the smallest testable units of the code are tested to check whether the individual functionality is working as intended. The main aim of unit testing is to find bugs in the isolated functionality and improve the quality of code.<\/p>\n\n\n\n<p>ReactJS is the popular JavaScript library for building complex user interfaces encapsulating the functionality into reusable, isolated, and independent smaller components.<\/p>\n\n\n\n<p>We will be using <strong>Jest<\/strong>, a JavaScript test runner which will execute all our unit tests, and <strong>React-testing-library<\/strong> to write the actual unit tests where we will be checking the behavior of our component (<em>rather than the implementation details of the code<\/em>) as supposed the way end user will be interacting with.<\/p>\n\n\n\n<p>Now let&#8217;s start the writing unit tests.<\/p>\n\n\n\n<div class=\"wp-block-ugb-heading ugb-heading ugb-a01a7d6 ugb-main-block\"><div class=\"ugb-inner-block\"><div class=\"ugb-block-content\"><h2 class=\"ugb-heading__title\"><strong>Step 1<\/strong><\/h2><p class=\"ugb-heading__subtitle\">Create a new react app using the below command<\/p><\/div><\/div><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app unit-test-demo\n<\/code><\/pre>\n\n\n\n<p>open <strong>package.json<\/strong> and you can ensure that both jest and react-testing-library will be installed by default so nothing needs to be installed manually.<\/p>\n\n\n\n<div class=\"wp-block-ugb-heading ugb-heading ugb-2796f84 ugb-main-block\"><div class=\"ugb-inner-block\"><div class=\"ugb-block-content\"><h2 class=\"ugb-heading__title\"><strong>Step 2<\/strong><\/h2><p class=\"ugb-heading__subtitle\">Create a simple component named UserData which accepts value through props and just displays that on the screen. So testing this is fairly easy and there will be only 2 scenarios to check when the userName is passed and when not.<\/p><\/div><\/div><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>import { React } from \"react\";\n\nconst UserData = ({ userName }) => {\n  return (\n    &lt;div data-testid=\"username\">\n        {userName?userName:'Anonymous'}\n    &lt;\/div>\n  );\n};\nexport default UserData;\n<\/code><\/pre>\n\n\n\n<p><strong>Note<\/strong>: I have provided <code>data-testid<\/code> an attribute to the div using which we can easily find our element using <code>getByTestId<\/code>and There are other ways to select the elements also eg ByRole, ByText, ByTagName&#8230;<\/p>\n\n\n\n<div class=\"wp-block-ugb-heading ugb-heading ugb-9415240 ugb-main-block\"><div class=\"ugb-inner-block\"><div class=\"ugb-block-content\"><h2 class=\"ugb-heading__title\"><strong>Step 3<\/strong><\/h2><p class=\"ugb-heading__subtitle\">Now create the file naming<strong> UserData.test.jsx<\/strong> which will help jest to identify and run the test file.<\/p><\/div><\/div><\/div>\n\n\n\n<p>What is the basic structure of testing code block? Let&#8217;s understand that first<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Create the test block which contains the descriptions and callback function where our test case resides. you can wrap multiple test blocks into a single test suite also although that&#8217;s completely optional.<\/li><li>render the component which you want to test <\/li><li>Now select the elements and interact with those elements like clicking, changing the input values, etc&#8230;<\/li><li>Next, you need to assert the values you might have changed or expected to validate your test cases.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>import React from \"react\";\nimport UserData from \"..\/UserData\";\nimport { render } from \"@testing-library\/react\";\n\ndescribe(\"User Data\", () => {\n  it(\"should render with default props\", () => {\n    const { getByTestId } = render(&lt;UserData \/>);\n    const element = getByTestId(\"username\");\n    expect(element.textContent).toMatch(\"Anonymous\")\n  });\n  it(\"should render with props provided\", () => {\n    const userName=\"Ellie Smith\"\n    const { getByTestId } = render(&lt;UserData userName={userName}\/>);\n    const element = getByTestId(\"username\");\n    expect(element.textContent).toMatch(userName)\n  });\n});\n<\/code><\/pre>\n\n\n\n<p>I have created 2 test cases for the above component one with the default state and another with the value passed through props and finally expecting the values using the assertion statement.<\/p>\n\n\n\n<div class=\"wp-block-ugb-heading ugb-heading ugb-9d58d7b ugb-main-block\"><div class=\"ugb-inner-block\"><div class=\"ugb-block-content\"><h2 class=\"ugb-heading__title\"><strong>Step 4<\/strong><\/h2><p class=\"ugb-heading__subtitle\">Now the last step is to run the unit test to validate your test cases using the command <code>npm run test<\/code> and this is how the result will look if all test cases passed.<\/p><\/div><\/div><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code> PASS  src\/components\/tests\/UserData.test.jsx\n  User Data\n    \u2713 should render with default props (5 ms)\n    \u2713 should render with props provided (2 ms)\n\nTest Suites: 1 passed, 1 total\nTests:       2 passed, 2 total\nSnapshots:   0 total\nTime:        0.312 s, estimated 1 s\n<\/code><\/pre>\n\n\n\n<p>Writing test cases for the pure function is fairly simple. Pure function means the functions if provided the same input always returns the same output but in reality, the code logic is much more complex which might involve performing side effects using react hooks and managing the state logic.<\/p>\n\n\n\n<p>So In this article, I have tried to cover the basics of unit testing and how to write and execute the tests with examples. Please provide your valuable constructive feedback\/suggestion as it will help in improving and sharing more knowledge with others.<\/p>\n\n\n\n<p>I have planned the next few articles covering the complex and advanced test cases involving react and Redux and<strong> uncovering the secret of 100% code coverage, How??.<\/strong><\/p>\n\n\n\n<p>You can find all code changes related to this series on my GitHub <a href=\"https:\/\/github.com\/bhuvnesh9758\/unit-test-demo\" data-type=\"URL\" data-id=\"https:\/\/github.com\/bhuvnesh9758\/unit-test-demo\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>https:\/\/github.com\/bhuvnesh9758\/unit-test-demo<\/strong><\/a><\/p>\n\n\n\n<p>I will be uploading the next article in this series soon. See you soon!!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Unit testing is an important part of the Software development life cycle and unit tests are written and executed by developers in which the smallest testable units of the code are tested to check whether the individual functionality is working as intended. The main aim of unit testing is to&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\">Read the post<span class=\"screen-reader-text\">Unit Testing In React: Introduction<\/span><\/a><\/div>\n","protected":false},"author":1,"featured_media":3267,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1],"tags":[676,677,913,1096],"class_list":["post-3264","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-infinity-fitness","tag-javascript","tag-jest","tag-react-testing-library","tag-unit-testing","excerpt","zoom","full-without-featured","even","excerpt-0"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.12 (Yoast SEO v26.8) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Unit Testing In React: Introduction | ManOrInfinity<\/title>\n<meta name=\"description\" content=\"Unit Testing in React. Introduction to react testing library. Jest and React. How react testing library works. how to implement react testing library\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Unit Testing In React: Introduction\" \/>\n<meta property=\"og:url\" content=\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\" \/>\n<meta property=\"og:site_name\" content=\"ManOrInfinity\" \/>\n<meta property=\"article:published_time\" content=\"2022-10-04T17:33:32+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-12-28T15:39:27+00:00\" \/>\n<meta name=\"author\" content=\"manorinfinity\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@manorinfinity\" \/>\n<meta name=\"twitter:site\" content=\"@manorinfinity\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"manorinfinity\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\"},\"author\":{\"name\":\"manorinfinity\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901\"},\"headline\":\"Unit Testing In React: Introduction\",\"datePublished\":\"2022-10-04T17:33:32+00:00\",\"dateModified\":\"2022-12-28T15:39:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\"},\"wordCount\":574,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901\"},\"image\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage\"},\"thumbnailUrl\":\"\",\"keywords\":[\"JavaScript\",\"jest\",\"react testing library\",\"unit testing\"],\"articleSection\":[\"Infinity Fitness\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\",\"url\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\",\"name\":\"Unit Testing In React: Introduction | ManOrInfinity\",\"isPartOf\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage\"},\"thumbnailUrl\":\"\",\"datePublished\":\"2022-10-04T17:33:32+00:00\",\"dateModified\":\"2022-12-28T15:39:27+00:00\",\"description\":\"Unit Testing in React. Introduction to react testing library. Jest and React. How react testing library works. how to implement react testing library\",\"breadcrumb\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage\",\"url\":\"\",\"contentUrl\":\"\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/manorinfinity.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Unit Testing In React: Introduction\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/#website\",\"url\":\"https:\/\/manorinfinity.com\/blog\/\",\"name\":\"ManOrInfinity\",\"description\":\"Thrive towards greatness\",\"publisher\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/manorinfinity.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901\",\"name\":\"manorinfinity\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"http:\/\/manorinfinity.com\/wp-content\/uploads\/2023\/06\/moi-logo.png\",\"contentUrl\":\"http:\/\/manorinfinity.com\/wp-content\/uploads\/2023\/06\/moi-logo.png\",\"width\":282,\"height\":260,\"caption\":\"manorinfinity\"},\"logo\":{\"@id\":\"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/image\/\"},\"description\":\"Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being\",\"sameAs\":[\"http:\/\/manorinfinity.com\"],\"url\":\"https:\/\/manorinfinity.com\/blog\/author\/manorinfinity\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Unit Testing In React: Introduction | ManOrInfinity","description":"Unit Testing in React. Introduction to react testing library. Jest and React. How react testing library works. how to implement react testing library","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/","og_locale":"en_US","og_type":"article","og_title":"Unit Testing In React: Introduction","og_url":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/","og_site_name":"ManOrInfinity","article_published_time":"2022-10-04T17:33:32+00:00","article_modified_time":"2022-12-28T15:39:27+00:00","author":"manorinfinity","twitter_card":"summary_large_image","twitter_creator":"@manorinfinity","twitter_site":"@manorinfinity","twitter_misc":{"Written by":"manorinfinity","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#article","isPartOf":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/"},"author":{"name":"manorinfinity","@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901"},"headline":"Unit Testing In React: Introduction","datePublished":"2022-10-04T17:33:32+00:00","dateModified":"2022-12-28T15:39:27+00:00","mainEntityOfPage":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/"},"wordCount":574,"commentCount":0,"publisher":{"@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901"},"image":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage"},"thumbnailUrl":"","keywords":["JavaScript","jest","react testing library","unit testing"],"articleSection":["Infinity Fitness"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/","url":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/","name":"Unit Testing In React: Introduction | ManOrInfinity","isPartOf":{"@id":"https:\/\/manorinfinity.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage"},"image":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage"},"thumbnailUrl":"","datePublished":"2022-10-04T17:33:32+00:00","dateModified":"2022-12-28T15:39:27+00:00","description":"Unit Testing in React. Introduction to react testing library. Jest and React. How react testing library works. how to implement react testing library","breadcrumb":{"@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#primaryimage","url":"","contentUrl":""},{"@type":"BreadcrumbList","@id":"https:\/\/manorinfinity.com\/blog\/2022\/10\/04\/unit-testing-in-react-introduction\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/manorinfinity.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Unit Testing In React: Introduction"}]},{"@type":"WebSite","@id":"https:\/\/manorinfinity.com\/blog\/#website","url":"https:\/\/manorinfinity.com\/blog\/","name":"ManOrInfinity","description":"Thrive towards greatness","publisher":{"@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/manorinfinity.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/1172b1895b5eb7e49cc8640e49255901","name":"manorinfinity","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/image\/","url":"http:\/\/manorinfinity.com\/wp-content\/uploads\/2023\/06\/moi-logo.png","contentUrl":"http:\/\/manorinfinity.com\/wp-content\/uploads\/2023\/06\/moi-logo.png","width":282,"height":260,"caption":"manorinfinity"},"logo":{"@id":"https:\/\/manorinfinity.com\/blog\/#\/schema\/person\/image\/"},"description":"Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being","sameAs":["http:\/\/manorinfinity.com"],"url":"https:\/\/manorinfinity.com\/blog\/author\/manorinfinity\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"_links":{"self":[{"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/posts\/3264","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/comments?post=3264"}],"version-history":[{"count":1,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/posts\/3264\/revisions"}],"predecessor-version":[{"id":3378,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/posts\/3264\/revisions\/3378"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/"}],"wp:attachment":[{"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/media?parent=3264"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/categories?post=3264"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/manorinfinity.com\/blog\/wp-json\/wp\/v2\/tags?post=3264"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}