<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yasaminkamali on Medium]]></title>
        <description><![CDATA[Stories by Yasaminkamali on Medium]]></description>
        <link>https://medium.com/@yasaminkamali?source=rss-c8b0f2739740------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3XRAT3BrNUaKh9_tpc0mXw.jpeg</url>
            <title>Stories by Yasaminkamali on Medium</title>
            <link>https://medium.com/@yasaminkamali?source=rss-c8b0f2739740------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:05:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasaminkamali/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Jest Mock for Unit Testing MERN Back-end]]></title>
            <link>https://javascript.plainenglish.io/jest-mock-for-unit-testing-mern-backend-983c1e3fef83?source=rss-c8b0f2739740------2</link>
            <guid isPermaLink="false">https://medium.com/p/983c1e3fef83</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Yasaminkamali]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 04:24:36 GMT</pubDate>
            <atom:updated>2021-10-27T06:46:09.693Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EJfQdZ-uaq8nIR4YVtJEbQ.png" /><figcaption>Mocking bird</figcaption></figure><p>Recently, I had to write some unit tests for a Node.js back-end that worked with multiple external services like Redis (database) and Kafka (message queueing). Although I had experience with Jest for Node.js unit testing, I had no idea what to do when functions were calling on external processes, such as doing a database lookup. This is where mock comes into the picture, it allows us to ‘mock’ a function’s implementation so we can test the accuracy of our code without worrying about everything else.</p><p>To explain this concept, I’m gonna use a simple Node.js -backend about restaurants 🌮! Our app can create restaurants with unique names and store them in MongoDB with mongoose.</p><p>This assumes you’re already familiar with Jest and Node.js, if not please read my <a href="https://javascript.plainenglish.io/unit-testing-node-js-mongoose-using-jest-106a39b8393d">other tutorial</a> on how to get started with Jest unit testing for Node.</p><h3>Section 1: App setup</h3><p>Once we initialise npm we just need to install express and mongoose. This is the bare minimum I’m going to use for this tutorial but feel free to have more ☕️</p><pre>// set up node<br>npm init<br>// install dependencies<br>npm i express mongoose</pre><h4>Model</h4><p>Our model is very simple. We just have a restaurant with a name, cuisine type and address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfPy-I8HtHZhpzL0u1wAdQ.png" /><figcaption>Restaurant Model</figcaption></figure><h4>Controllers</h4><p>We will try to write tests for a function that creates a new restaurant. The function simply takes a name, location and cuisine type, and if the name has not already been used it creates a new restaurant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vhtda97fusRgdUT7ig5hig.png" /><figcaption>Function to create a new restaurant: controllers/createRestaurant.js</figcaption></figure><p>This function will be incorporated into our app like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2s_0jm8r-MheTqx6ob1Ag.png" /><figcaption>Controller: controllers/index.js</figcaption></figure><p>By splitting the function up, we can easily unit test it later. Finally, the app’s entry point will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n392-ENU9RkPWZQC6Tk_nQ.png" /><figcaption>Entry point: index.js</figcaption></figure><h3>Section 2: Install Jest</h3><p>We can use npm to install the Jest framework for our testing.</p><pre>npm install jest</pre><h3>Section 3: Testing</h3><p>One way which I have found to be clean and easy to understand is it having unit tests in the same folder as the files which they are testing. Hence, we will create a new file in controllers folder. One key thing is the naming of our test files. They have to end in .test.js . This is how Jest is able to identify them and run our tests!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*jvClHqxTCkx33eq1J8YRlA.png" /><figcaption>Folder structure for tests</figcaption></figure><h4>First Jest — oops, Test 😎</h4><p>Finally, we can proceed to write our first test! For our first test using mock , we will test a case where we try to create a restaurant with a name that has already been used. This should throw an error and we want to make sure this happens.</p><p>To mock this behaviour, all we need to say is:</p><pre>Restaurant.findOne = jest.fn().mockReturnValueOnce({<br>     name: &quot;Amy&#39;s&quot;<br>});</pre><p>The anatomy of mock is like this.</p><figure><img alt="jest mock structure" src="https://cdn-images-1.medium.com/max/600/1*su6JNm5mVBw8LGxrh8DUsQ.jpeg" /><figcaption>Mock anatomy</figcaption></figure><ol><li>functionToMock: This is the function whose behaviour you want to change for your test. For example for our test, we need to mock Restaurant.findOne to return a value instead of actually searching the database.</li><li>jest.fn(): This is common to all mocks</li><li>mockReturnValueOnce : This specifies what we want to mock. If all you care about is the return value of the function, you can use mockReturnValueOnce . Let’s say instead, you want to test when functionToMock throws an error. In that case, you would use mockImplementation . Jest provides a great list of options for this: <a href="https://jestjs.io/docs/mock-function-api">https://jestjs.io/docs/mock-function-api</a>.</li><li>yourReturnValue : This is where you place your desired behaviour/return value.</li></ol><p>It should be clear by now that we’re just telling jest , “Hey Jest, forget about what the actual implementation of a function is, instead do what I tell you to 😎”. Awesome right! We don’t have to worry about creating a fake database that acts the way we want in every test, instead, we can just tell jest to return the values we expect from the database calls.</p><p>Here is a full example of how we can use jest’s mock. First, we mock Model.findOne and then we need to mock the Model.prototype.save function. We’re passing a function that does nothing to the Restaurant.prototype.save which means, when jest comes across our code in controllers/createRestaurant.js that calls restaurant.save() , it simply does nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3azrcjuU92ln6WWEQ_Fjzg.png" /><figcaption>First unit test: controllers/createRestaurant.unit.test.js</figcaption></figure><p>It’s important to note we could use mockImplementation instead of mockReturnValue. For example, for Restaurant.findOne we could instead say:</p><pre>Restaurant.findOne = jest.fn().mockImplementation(() =&gt; {<br>    return {<br>        name: &quot;Amy&#39;s&quot;<br>    }<br>})</pre><p>This would behave in the same way, as we are passing it a function that just returns a name. If you don’t believe me, try it out!</p><h4>Run Test with Coverage</h4><p>Now it’s time to check everything is still working and I always like adding coverage to my tests so I have an idea of how I’m doing. With Jest, this is very simple. In package.json, you need to add this script:</p><pre>&quot;test&quot;: &quot;jest --coverage --verbose&quot;</pre><p>Now, when you run npm run test , you will see your coverage results as well 🥳</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bVy4h0MWOjKGAw4Hty3qPA.png" /><figcaption>Running tests</figcaption></figure><h3>Extra: Mocking Logs</h3><p>Most applications have some sort of logging and it&#39;s worthwhile to test that we are logging the correct information. In your function, you will be logging information, warnings and errors most probably using a third-party package. Similar to a when we test functions involving a database, we can mock the behaviour of our logger in the tests.</p><p>Since this tutorial isn’t about logging, I will just create a dummy function which just returns an empty object that will act as our logger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*fHEnBCzKRunvImiVlFBhAA.png" /><figcaption>utils/logger</figcaption></figure><p>In your application, this will be a proper helper for a logging system such as a winston logger. Let’s say we wish to log all errors (line 19) as well as an info log whenever we successfully create a restaurant (line 29).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YUO_lZ7QkTRhAuwtq2xk1g.png" /><figcaption>Adding logging: controllers/createRestaurant.js</figcaption></figure><p>Before we run any of our tests, we need to add the following at the top of our test file. This is an example of a logger with two levels: info and warn. If your logger has more levels that you use, feel free to add to this.</p><pre>const mockInfo = jest.fn();<br>const mockWarn = jest.fn();</pre><pre>// mocking Logging<br>jest.mock(&quot;../utils/Logger&quot;, () =&gt; {<br>    return {<br>        getLogger: () =&gt; ({<br>            info: mockInfo,<br>            warn: mockWarn<br>        })<br>    }<br>})</pre><p>What this means is that when createRestaurant calls the getLogger function in &quot;../utils/Logger&quot; file, instead of creating and providing the real logger function, return the empty functions we have made: mockInfo and mockWarn for info and warn respectively.</p><p>How can we check that we’re calling the log functions in our tests? 🤔</p><p>Jest offers a toHaveBeenCalledWith function which checks wether a function has been called with certain parameters. Let’s write a test for a case where we successfully create a restaurant and check the logger is working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuGQznp8Xy-cfZkCmJMqRQ.png" /></figure><p>Finally, checking our tests are all passing…look at that coverage! 😯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH85Sozh3szd_bUaWTb47g.png" /></figure><h3>And we’re done 🥳</h3><p>And that is it for using mock . It can make life so much simpler when you’re writing your unit tests as it removes the need to worry about the behaviour of external functions that you’re using. You can just ensure <strong>your</strong> function works given specific input, which is what unit testing is all about!</p><p>Please reach out if there’s any problems or you need more guidance on a specific point. 😊</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983c1e3fef83" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/jest-mock-for-unit-testing-mern-backend-983c1e3fef83">Jest Mock for Unit Testing MERN Back-end</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Static Site Deployment to AWS]]></title>
            <link>https://yasaminkamali.medium.com/automate-static-site-deployment-to-aws-c6ea81e57824?source=rss-c8b0f2739740------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ea81e57824</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[static-site]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Yasaminkamali]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 11:02:21 GMT</pubDate>
            <atom:updated>2021-03-27T01:33:22.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*biURNdmQ2JDCgNqUposuNQ.png" /></figure><p>If you’ve made a static site then it’s pretty easy to make it live using AWS’s S3 buckets. The problem is every time you make a change (like add a new page), you’ll need to update your S3 bucket manually. If you’re also using CloudFront (to reduce latency, to Gzip, etc.) then you’ll need to update that too.</p><p>We can automate this process so you don’t have to worry about these tedious tasks. There are two steps:</p><ol><li>Create a pipeline to update S3 every time you push changes to GitHub</li><li>Clear CloudFront’s cache</li></ol><h3>Step 0: Set up GitHub Repository</h3><p>If you’re already using a repository then you can skip this. Otherwise, you should set up a free GitHub account and add your code to the master branch.</p><h3>Step 1: S3</h3><p>The goal is so that every time you push changes to your master branch, the S3 bucket from which the site is being hosted gets updated as well. AWS offers a simple solution for this: <strong>CodePipeline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wD1Tt4eU__Cp-xr6TLFQg.png" /><figcaption>AWS’s CodePipeline as of 2021</figcaption></figure><blockquote>Make sure your region is the same as where your S3 buckets are.</blockquote><p>To get started press <strong>Create pipeline</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oINSrzasOcSASicCT3Nd5A.png" /><figcaption>Pipeline settings</figcaption></figure><p>I chose the name s3_cont_deploy but it can be anything.</p><p>Before clicking next, open <strong>Advanced Settings</strong> on the same page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HekZ3ux6-fxPT8qwyoe3g.png" /></figure><p>Choose <strong>Custom Location</strong> and search for the bucket where your static site is currently being hosted from.</p><p>Leave Encryption Key as default. Now press next!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtj5_u5czh9YUBdRfc8Y5Q.png" /><figcaption>CodePipeline Source Provider</figcaption></figure><p>Search for GitHub (version 2) as your Source provider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mCone0eGldJtr1zpx4CnQ.png" /><figcaption>GitHub (Version 2) Source Provider</figcaption></figure><p>Then you will be asked to specify a connection. If you have connected to your GitHub account from AWS before then simply search for that connection name. Otherwise, press <strong>Connect to Github</strong>.</p><p>Once you press <strong>Connect to Github</strong> a new tab will open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Mg4NCqbT-P8NoGJSPSj1g.png" /><figcaption>Connect to GitHub</figcaption></figure><p>From here you can follow the instructions to prove you own the GitHub account.</p><p>Once you’re done, go back to the CodePipeline page. You should now see the new connection you just made as one of the options.</p><p>Add in details such as the repository for your code and the branch from which you would like to deploy. I recommend setting this as master.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvWhzltnT2BMEfl_4mbYtA.png" /></figure><p>Next stage is specifying the build provider. Skip this stage.</p><p>Next is Deploy Provider. Search for Amazon S3 and then select your bucket’s region and name (mine is called alkypal.com.au). Tick Extract file before deploy and hit next!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmN3Knplg_5itvrH6ecS0w.png" /><figcaption>deploy provider</figcaption></figure><p>Now you simply need to review the pipeline and press create.</p><h4>Do a quick check 👀</h4><p>To make sure everything is working as expected, add an image file to your repository. It does not matter what it is, this is just for testing.</p><p>Make sure you add, commit and push your code to the master branch.</p><p>Then head over to <strong>CodePipeline</strong> and select the pipeline that has the name which you chose earlier and you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwU67efF2B9cxNqkB65Wmw.png" /></figure><p>Wait for the <strong>Deploy</strong> stage to finish (you will know once it turns green and changes status to Succeeded).</p><p>Now head over to S3 and select your bucket. Check and make sure that the image is in your bucket. If it is, then your pipeline is working as expected. Make sure you delete the image from your repository and your S3 bucket!</p><h3>Step 2: Cloudfront</h3><p>If you’re using Cloudfront (which most websites do) then you need to do the following step as well to ensure changes do appear in browser. This stage is a bit long so I have broken it down further into 3 small steps:</p><ol><li>Setup an IAM role</li><li>Setup lambda function that uses the IAM role made in step 1</li><li>Add your S3 bucket as a trigger for the lambda function from step 2</li></ol><h4>Step 1: Set up IAM Role</h4><p>An IAM role can be used to give permissions to a resource to perform actions on other resources. In our case, we want to create a role that will give permissions to lambda to perform actions on S3, Cloudfront and CloudWatch.</p><p>After searching <strong>IAM</strong>, select <strong>Roles </strong>and then select <strong>Create role.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtMK_aPTY5sgS-HuaOHRJg.png" /><figcaption>IAM Roles</figcaption></figure><p>Select <strong>AWS Service</strong> and then <strong>Lambda</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q38rcmr6z-QrsXk6Hjl5Yw.png" /><figcaption>Create IAM Role for lambda service</figcaption></figure><p>As mentioned before, we need to add 3 policies.</p><ol><li>S3: Search for the term below and tick the policy.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYpDI7MdOfKM7_dV_VS7Pw.png" /><figcaption>Step 1: add AmazonS3FullAccess Policy</figcaption></figure><p>2. CloudWatch: Once again tick the option for full access</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QuymnJXYiHqkS-GPtRk09Q.png" /></figure><p>3. CloudFront: For this select <strong>Create Policy</strong> which will take you to a new tab. Select JSON and insert the following code snippet:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: &quot;s3:*&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::*&quot;<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;cloudfront:CreateInvalidation&quot;,<br>                &quot;cloudfront:GetInvalidation&quot;,<br>                &quot;cloudfront:ListInvalidations&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>Now go back to <strong>create role</strong> page and select your newly created policy.</p><p>Go to next and add role name, I chose lambda_s3. Create the role!</p><h4>Step 2: Create Lambda Function</h4><p>Make sure you select Author from Scratch and add these settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHI3hxb2PGopra2mvesUNg.png" /></figure><p>This is where we can use the role we just made to give permissions to this lambda function.</p><p>Once you create the function, you will be taken to your newly created function which currently does <em>nothing </em>😩</p><p>We need to add some code. In the Code source add in the following code snippet and press deploy. This snippet is by <a href="https://medium.com/u/cee15f751d86">Yago Nobre</a> in <a href="https://medium.com/@yagonobre/automatically-invalidate-cloudfront-cache-for-site-hosted-on-s3-3c7818099868">his article</a>.</p><pre>from __future__ import print_function<br> <br>import boto3<br>import time<br> <br>def lambda_handler(event, context):<br>    path = &quot;/&quot; + event[&quot;Records&quot;][0][&quot;s3&quot;][&quot;object&quot;][&quot;key&quot;]<br>    bucket_name = event[&quot;Records&quot;][0][&quot;s3&quot;][&quot;bucket&quot;][&quot;name&quot;]<br>   <br>    client = boto3.client(&#39;s3&#39;)<br>    tags = client.get_bucket_tagging(Bucket=bucket_name)<br>    for tag in tags[&quot;TagSet&quot;]:<br>        if tag[&quot;Key&quot;] == &quot;distribution_id&quot;:<br>            distribution_id = tag[&quot;Value&quot;]<br>            break<br>   <br>    client = boto3.client(&#39;cloudfront&#39;)<br>    invalidation = client.create_invalidation(DistributionId=distribution_id,<br>        InvalidationBatch={<br>            &#39;Paths&#39;: {<br>                &#39;Quantity&#39;: 1,<br>                &#39;Items&#39;: [path]<br>        },<br>        &#39;CallerReference&#39;: str(time.time())<br>    })</pre><p>It should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZa5VcZRLuhnCDU8npdYiA.png" /><figcaption>Lambda function to invalidate cloudfront</figcaption></figure><h4>Step 3: Add S3 as a trigger</h4><p>Go back to your S3 bucket and under properties you will find <strong>Event notifications</strong>. Once you press create an event notification you should see this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axBk1hPyF0X_XXRmjTXNXw.png" /></figure><p>Give your notification a name. Leave the prefix and suffix emtpy (we want lambda to trigger for every change).</p><p>Under Event Types, select all create and delete events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nwV7CwNEwYHvP3FoUz_xQ.png" /><figcaption>Trigger for all delete and create events in bucket</figcaption></figure><p>Select the lambda function we just made. And save changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFZLR9fxGjLD3mDA6uQQ7A.png" /><figcaption>Select the function that will be triggered</figcaption></figure><p>Finally, go back to CloudFront and find your CloudFront ID. In your S3 bucket under properties add a tag with the Key “distribution_id” and the value of the CloudFront ID.</p><h3>Making sure it works…</h3><p>To make sure yours changes are automatically being deployed, you need to turn off your browser’s caching.</p><p>Now just change one of the files of your website. Hard refresh the page (make sure no browser caching) and you will see the changes!</p><p>Done!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ea81e57824" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB/Mongoose Schema Optimisation]]></title>
            <link>https://javascript.plainenglish.io/mongodb-mongoose-schema-optimisation-ed06b3382099?source=rss-c8b0f2739740------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed06b3382099</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Yasaminkamali]]></dc:creator>
            <pubDate>Wed, 10 Mar 2021 11:29:16 GMT</pubDate>
            <atom:updated>2021-03-10T11:29:16.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>3 MongoDB/Mongoose Schema Optimisation Techniques</h3><p>In this article, I’m gonna go over three things to consider when creating Mongoose schemas to improve the performance of your app’s queries.</p><h3>1. Embed vs Reference</h3><p>Deciding the schema will have significant conquences on the app performance because it affects the queries we can make. Personally, coming from an SQL background I’m used to having relations between objects.</p><p>For example, a dog belongs to a human and we can establish this using a foreign key.</p><p>Mongoose offers something similar in the form of ‘references’. But, just because it’s there doesn’t mean it should be used and abused.</p><p>For example, let’s say you have an app that shows a user’s details. Here are two possible ways you can represent the schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*YefyZBCu7ZW7aa9t5P-pcQ.png" /><figcaption>Option 1: Referencing similar to how it would be with SQL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*gYiVupMtqj-ULp8eMpDQUg.png" /><figcaption>Option 2: Embedding documents</figcaption></figure><p>The second option is showing how to embed documents. If you’re from an SQL background you&#39;re probably more familiar with the first method but that would require you to call .populate() every time you want to view details about the image of each user.</p><h4>When to embed or reference</h4><ul><li>Embedding is preffereable when the embedded document is unlikely to be used on it’s own. For example, if your app is going to have a page which shows all the photos in the database and doesn’t require any information about the user who owns the photo, then embedding would not be the most performant option.</li><li>Embedding is <strong>not</strong> ideal if you’re expecting the embedded data to be updating frequently.</li></ul><p>So keep these points in mind when you’re trying to show relationships in mongo.</p><h3><strong>2. Indexing</strong></h3><p>Mongo documents have a primary index of _id. You can add more indexes to your model if there is an attribute which you often query by. For example, if we often need to search for a user by their name we can create an index for that.</p><pre>personSchema.index({ name: 1 })</pre><p>This creates a single index for the name attribute with the documents sorted in ascending order.</p><p>We can also create a composite index if we’re often required to query a person by their name <strong>and</strong> email.</p><pre>personSchema.index({ name: 1, email: 1 })</pre><h4>Index in Moderation</h4><p>It is important to note however, that you shouldn’t go adding an index for every single attribute you ever search by.</p><p>Indexes do require maintenance (every time there is a CRUD operation) and they take up space. Hence, adding too many may cause the overhead to outweigh the benefits.</p><h3>3. Virtual Populate</h3><p>Suppose we have a one to many relationship between Person and Blog. A person can write many blogs but a blog can only have one author.</p><p>In this case, we reference the author in the Blog’s schema (very similar to a foreign key in SQL).</p><pre>const blogSchema = ({<br>    title: String,<br>    tags: [{<br>        type: String<br>    }],<br>    author: {<br>        type: Schema.Types.ObjectId,<br>        ref: &#39;Person&#39;<br>    }<br>})</pre><p>Now let’s say we want to find out all the blogs written by a person. One way to achieve this is to create a list of references to Blog in the Person model.</p><pre>const personSchema = ({<br>    name: String,<br>    blogs: [{<br>        type: Schema.Types.ObjectId,<br>        ref: &#39;Blog&#39;<br>    }]<br>})</pre><p>The problem with the modelling is that the blogs array can became infinitely large. Instead, we can should virtual populate!</p><pre>const personSchema = ({<br>    name: String<br>})</pre><pre>personSchema.virtual(&#39;blogs&#39;, {<br>    ref: &#39;Blog&#39;,<br>    localField: &#39;_id&#39;,<br>    foreignField: &#39;author&#39;<br>})</pre><p>Now to find all the blogs written by a person with personId:</p><pre>const blogs = await Person.findById(personId).populate(&#39;blogs&#39;)</pre><h4>Conclusion</h4><p>These are just some ways to improve your modelling. I hope this article has helped you when it comes to designing your mongoose data models!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed06b3382099" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mongodb-mongoose-schema-optimisation-ed06b3382099">MongoDB/Mongoose Schema Optimisation</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: How to Transition from Login Screen to Tab Bar Controller?]]></title>
            <link>https://yasaminkamali.medium.com/ios-how-to-transition-from-login-screen-to-tab-bar-controller-b0fb5147c2f1?source=rss-c8b0f2739740------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0fb5147c2f1</guid>
            <category><![CDATA[user-authentication]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Yasaminkamali]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 08:43:16 GMT</pubDate>
            <atom:updated>2021-03-08T12:57:37.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RP5b5vnWy91YkVs5P8ElSg.png" /></figure><p>Most app users expect that once they’ve logged in, they should remain logged in unless they explicitly request to log out.</p><p>A simple way to achieve this is by following this navigation flow below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1zr2KfAgpSb35FYkqGB2A.png" /><figcaption>Poor navigation flow for authentication</figcaption></figure><p>The main problem with using this method is that we continue to push screens onto the stack, increasing memory usage and eventually slowing down your app.</p><p>In this article, I will show you how to avoid this issue by changing your root view controller based on the user’s login status.</p><p>I will also show you how to pass data from the login screen to the tab bar using the following flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRouIR36bqz9tN7cjMHHIA.png" /><figcaption>Good navigation flow for authentication</figcaption></figure><h3><strong>Example App</strong></h3><p>This section discusses the setup of the example app that I’ll be using to explain the transition. I highly recommend you skim read over this so you’re familiar with the setup!</p><h4>Storyboard</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3_iVhLPfeCtq59U9-3RvA.png" /><figcaption>App’s storyboard</figcaption></figure><p>I created a custom class for the tabBarController called CustomTabBarController and it has two tab items:</p><ol><li>TabOneNavigationController that leads to TabOneViewController</li><li>TabTwoViewController that has no navigation controller</li></ol><p>In both examples, we are passing the userId of the logged in user to the tab bar controller and displaying the result on screen.</p><p>If the user is logging in then theuserId will be passed from LoginViewController.swift.</p><p>If the user is already logged in and has just launched the app we will pass it from sceneDelegate.swift.</p><h4>User</h4><p>In a real iOS app, you would probably be using a particular method from your chosen database to discover if the app has any logged in users.</p><p>However, to make this tutorial applicable to everyone, I will simply be using a dictionary that has key pair values of a made up user.</p><p>I am adding this dictionary to LoginViewController.swift and sceneDelegate.swift.</p><pre><strong>var</strong> appUser : [String:String]? = [<br>    &quot;name&quot;: &quot;Yasmin&quot;,<br>    &quot;password&quot;: &quot;abcd&quot;,<br>    &quot;id&quot;: 1<br>]</pre><h4>CustomTabBarController</h4><p>In here we create a variable called userId. Lines 26–32 show how to pass userId if there is a navigation controller:</p><p>CustomTabBarController -&gt;TabOneNavigationController -&gt; TabOneViewController</p><p>and lines 34–35 are an example of no navigation controller:</p><p>CustomTabBarController -&gt;TabTwoViewController</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWMbeMXItShmXmRW_c6Oeg.png" /><figcaption>CustomTabBarController Class passing data to view controllers</figcaption></figure><h4>TabOneViewController</h4><p>Here we have the userId variable that will be assigned to the UILabel and shown on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*ueMCOzWNL_b0bFsBh7XyfA.png" /><figcaption>View Controller showing userID passed on from login/sceneDelegate on screen</figcaption></figure><p>TabTwoViewController will be the same.</p><p>Now that we’ve covered the sample app, let’s see how we can transition from the login controller to the tab controller and pass the user’s ID along.</p><h3>Step 1: Add Storyboard IDs</h3><p>If you haven’t done so already, add the storyboard ID to the LoginNavigationController, CustomTabBarController &amp; TabOneNavigationController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7ZGpMP8BmOXcDpLGzzkbQ.png" /><figcaption>Adding storyboard ID to LoginNavigationController</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0z5CqPwYQksSkSGRX1FraQ.png" /><figcaption>Adding storyboard ID to CustomTabBarController</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq2s-_IrkUSjeIzELV5J5w.png" /><figcaption>Adding storyboard ID to TabOneNavigationController</figcaption></figure><h3>Step 2: Configuring SceneDelegate</h3><p>In sceneDelegate‘s willConnectTo session we can specify our root scene (initial view). In here, we can check if our app has a logged in user and set the root view accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EHWU1vIiA-cavQ-P29UUg.png" /><figcaption>SceneDelegate.swift setting initial root view on app launch</figcaption></figure><p>If you start up your app, you will see that our sceneDelegate is now handling the initial view and we can pass the ID over to our two tab screens.</p><p>We’re almost done so hang in there!</p><h3>Step 3: Create a Helper Function to Set Root ViewController</h3><p>What happens when a user logs in?</p><p>What we want to happen is to change the root view controller to CustomTabBarController.</p><p>For that, we will create a function in sceneDelegate.swift which we can then call upon in the rest of the app.</p><p>I’m going to call the function setRootViewController and it’s arguments will be the view controller that we are changing to as well as the userId of the logged in user.</p><p>We only pass the userId if the user is logging in (not when they’re logging out), hence why it can be nil.</p><pre><strong>func</strong> setRootViewController(<strong>_</strong> vc: UIViewController, <strong>_</strong> userId: Int? = nil) {<br>     <strong>if</strong> <strong>let</strong> window = <strong>self</strong>.window {<br>          // if we are logging in, pass the userId<br>          <strong>if</strong> <strong>let</strong> customTb = vc <strong>as</strong>? CustomTabBarController {<br>               customTb.userId = userId<br>          }<br>          window.rootViewController = vc<br>     }<br>}</pre><h3>Step 4: Handle Login &amp; Register</h3><p>Now in LoginViewController.swift, in the login function, we can call on setRootViewController .</p><pre><strong>let</strong> storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: <strong>nil</strong>)</pre><pre><strong>let</strong> mainTabBarController = storyboard.instantiateViewController(identifier: &quot;CustomTabBarController&quot;) <strong>as</strong>! CustomTabBarController</pre><pre>(UIApplication.shared.connectedScenes.first?.delegate <strong>as</strong>? SceneDelegate)?.setRootViewController(CustomTabBarController, String(appUser[&quot;id&quot;] ?? &quot;0&quot;))</pre><p>It’s that simple!</p><p>Make sure that you repeat this for RegisterViewController as well.</p><h3>Step 5: Handle Logout</h3><p>Wherever you handle your logout function, follow up with this code:</p><pre><strong>let</strong> storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: <strong>nil</strong>)</pre><pre><strong>let</strong> loginNavController = storyboard.instantiateViewController(identifier: &quot;LoginNavigationController&quot;)</pre><pre>(UIApplication.shared.connectedScenes.first?.delegate <strong>as</strong>? SceneDelegate)?.setRootViewController(loginNavController)</pre><p>As you can see, for logging out, we don’t need to pass the userId as a parameter.</p><p>If you test logging in and out of your app, you will notice it almost seems a bit glitchy and most well developed apps use some sort of animation when changing between screens.</p><h3>Step 6: (Optional) Adding Animation</h3><p>Back in setRootViewController(), we can add an animation to the screen change.</p><pre><strong>func</strong> setRootViewController(<strong>_</strong> vc: UIViewController, <strong>_</strong> userId: Int? = nil) {<br>     <strong>if</strong> <strong>let</strong> window = <strong>self</strong>.window {<br>          // if we are logging in, pass the userId<br>          <strong>if</strong> <strong>let</strong> customTb = vc <strong>as</strong>? CustomTabBarController {<br>               customTb.userId = userId<br>          }<br>          window.rootViewController = vc</pre><pre>          // adding animation</pre><pre>          UIView.transition(with: window, <br>                            duration: 0.8,<br>                            options: .transitionCurlDown, <br>                            animations: <strong>nil</strong>)<br>     }<br>}</pre><p>I have chosen transitionCurlDown but feel free to try out all the other animation options and pick whichever suits your app the most!</p><p>View the other options here:</p><p><a href="https://developer.apple.com/documentation/uikit/uiview/animationoptions">UIView.AnimationOptions | Apple Developer Documentation</a></p><p>Done!!!!</p><p>Please comment or private message me if there’s anything that isn’t very clear.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0fb5147c2f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Node.js + Mongoose Using Jest]]></title>
            <link>https://javascript.plainenglish.io/unit-testing-node-js-mongoose-using-jest-106a39b8393d?source=rss-c8b0f2739740------2</link>
            <guid isPermaLink="false">https://medium.com/p/106a39b8393d</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yasaminkamali]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 01:07:50 GMT</pubDate>
            <atom:updated>2021-10-27T04:33:20.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BFklk0QyI9b1PSQscUTkjA.png" /></figure><p>Unit testing is not the answer to everything, but it sure as hell does prevent a few embarrassing and mind numbing situations. Sometimes, no matter how careful you are when programming, some bugs go unnoticed and the simplest way to catch them before anyone else is unit testing.</p><p>In this guide, I will show you how to unit test your MERN stack’s backend using Jest. Specifically, Node.js and Mongoose.</p><p>If you’re experienced with Node.js then you can skip to Step 2 which details how to test your functions.</p><h3><strong>Step 1. Set up express backend</strong></h3><p>This step should be pretty straight forward for most people. All you really need to do is set up npm, install a few packages and make sure you can start your server successfully. I’m using nodemon but feel free to use npm as well.</p><pre>npm init -y<br>npm i express mongoose nodemon</pre><p>This is what your project should be looking like by this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6w80JrdHIarIu7CQ-8s6Q.png" /><figcaption>basic set up in index.js</figcaption></figure><p>As we’re only concerned with testing the application, we only need a very simple API and since everyone likes food, I thought why not make <em>another</em> Restaurant API!</p><p><strong>The Restaurant Schema</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGs4P9zZx6a9wK396A9lig.png" /><figcaption>Restaurant model in model/Restaurant.js</figcaption></figure><p>Nothing about this should be new, but the enum for cost may be confusing to some people.</p><p>The enum is simply set up to add an extra step of validation to each restaurant object, with regards to their cost property. What this means is “A restaurant’s cost has to be a string and can only be one of the values ‘$’, ‘$$’, ‘$$$’. If no value is provided then give the restaurant a cost of ‘$$’.” Pretty simple, right?</p><p>One of our tests will cover a case where the string passed in for cost is not one of the strings in the enum. At this point the database will fail to save the new object and we will see how to handle that kind of error.</p><h4><strong>Create Restaurant Function</strong></h4><p>Our first function will be to create a restaurant given a name, location and budget.</p><p>The only reason why it should fail to create a restaurant other than a database error, is if another restaurant already has the given name (see lines 10–11), or, if the restaurant’s cost is not one of the strings in the enum mentioned earlier (see model/Restaurant.js).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6celQRmisliyUwVgyhbtLw.png" /><figcaption>helper function to create a new restaurant in controller/createRestaurant.js</figcaption></figure><p>If it succeeds, it will return the id of the newly created restaurant.</p><h4><strong>Create Restaurant Post Method</strong></h4><p>This step is not necessary for testing but just incase you’re not used to using helper functions, I wanted to include how you could incorprate them into your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvw2nTMpumVyHN5g4Gmf2A.png" /><figcaption>controller/index.js</figcaption></figure><p>As you can see in the image above, createRestaurant(name, loc, cost) that we created earlier is being called in the post request and all of this is wrapped in a try catch statement so that if an error arises (eg. same name used twice) we are handling it.</p><h3><strong>Step 2. Install Jest and mongodb-memory-server</strong></h3><p>As mentioned in the article title, we will be using Jest to run our tests.</p><p>Jest provides methods to create, organise and run your tests. It is one of the most popular testing frameworks as it focuses on simplicity so that you can focus on the logic behind the tests.</p><blockquote>“Jest is a delightful JavaScript Testing Framework with a focus on simplicity.”</blockquote><p>The second package we must install is mongodb-memory-server. If you’re already familiar with how mongo works, you’ll know that you create a cluster that stores all of you app’s data. Most applications will be writing/querying/updating the database somewhat regularly and therefore, it is important to ensure that your interactions with the database are producing the desired outcome.</p><blockquote>The mongodb-memory server creates a ‘cluster’ which only exists in your device’s main memory and is not physically stored to disk.</blockquote><p>Therefore, once your application terminates, the database instance will no longer exist. This method will also be faster than if you were to mock the interactions with the database.</p><p>Now that we have the theory covered, let’s install both packages:</p><pre>npm i mongodb-memory-server jest</pre><h3><strong>Step 3. Handle in-memory Server</strong></h3><p>To make sure we’re not repeating code and keeping good style, it’s good to create and then export functions for handling the in-memory database and then call on these exported functions as they’re required throughout the rest of the project.</p><p>The mongodb-memory-server package we installed earlier has a very helpful github page that explains how to connect and create a db instance:</p><p><a href="https://github.com/nodkz/mongodb-memory-server#simple-server-start">nodkz/mongodb-memory-server</a></p><p>If you don’t want to read through the documentation, then the following code will be enough for you to get started with your unit testing.</p><p>Special thanks to <a href="https://dev.to/paulasantamaria">Paula Santamaría</a> for her article where she provides this module. I will link to her article at the end of this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2yWnnOaXrzXReHBk-ofHQ.png" /><figcaption>Handling interactions with in-memory database: tests/db.js</figcaption></figure><p>The connect and closeDatabase methods should be pretty self explainable, however, you may be wondering why we need a clearDatabase function as well.</p><p>When it comes to unit testing, each test should start on a blank canvas, which means that there should be no existing data in the database when we start a new test. Therefore, every time a test ends, we will call the clearDatabase function.</p><h3><strong>Step 4. Set up the test file</strong></h3><p>First, in our tests folder we will be keeping all the files which includes tests. It is important when it comes to naming the files to ensure that they’re done in this manner: fileName.test.js</p><p>Before any of the tests are run, we will need to connect to the in-memory database. Lucky for us, we have already created and exported a method to do that in tests/db.js. Similarly, we need to disconnect and drop the database once all tests are run. Finally, after each individual test, we must clear the database.</p><p>Now all we need to do is add this to the top of every test file:</p><pre>const db = require(&#39;./db&#39;)</pre><pre>beforeAll(async () =&gt; await db.connect())</pre><pre>afterEach(async () =&gt; await db.clearDatabase())</pre><pre>afterAll(async () =&gt; await db.closeDatabase())</pre><h3><strong>Step 5. Anatomy of a Test in Jest</strong></h3><p>With everything set up, we can now focus on our first test for the createRestaurant function.</p><p>Jest offers a way to organise our tests. Consider the following example for testing an asynchronous function that takes in an integer and returns the number as an integer and a string:</p><pre>describe(&#39;First Group Of Tests&#39;, () =&gt; {</pre><pre>    it(&#39;First Test&#39;, async done =&gt; {<br>        const result = await numberFunc(10)<br>        expect(result.word).toBe(&quot;ten&quot;)<br>        expect(result.number).toBeGreaterThan(10)<br>        done()</pre><pre>    })<br>    it(&#39;Second Test&#39;, async done =&gt; {<br>        const result = await numberFunc()<br>        expect(result).toBeNull()<br>        done()</pre><pre>    })</pre><pre>})</pre><p>Key points of this are:</p><ul><li>The describeblock is a way to place similar tests together. For example, if you’re testing the createRestaurant function and want to make sure it can handle various name lengths, you can place all those tests into the same describe block.</li><li>The it block represents each individual test.</li><li>The most important part of an it block for an asynchronous test is to ensure you include the done() at the end of the test. If you don’t, the test will be finished before any asynchronous call completes and your tests will fail. The way that Jest explains the importance of done()in an async function is:</li></ul><blockquote>“Jest will wait until the done callback is called before finishing the test.”</blockquote><ul><li>expect is very similar to assert in other languages. It is the way we can check to ensure that our functions are retrieving/creating the objects we want them to. Whilst there are many different ways to use expect , I have only shown 3 options here. For more, check out <a href="https://jestjs.io/docs/en/expect">https://jestjs.io/docs/en/expect</a></li></ul><h3><strong>Step 6. Testing </strong>createRestaurant()</h3><p>As the tests are run from top down, it’s good to keep the most simple/basic test at the top of the file. What I mean by this is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xIF-oznv8cr9HcGAd8QHUw.png" /><figcaption>example test suite to show order of tests running in Jest</figcaption></figure><p>Basically, the order of the tests in a file will matter.</p><p>So it’s good to start with a test for the most basic requirement of a function to make sure it works before moving on to more complicated cases.</p><p>So going back to testing createRestaurant() , the most basic test case would be creating one restaurant with a valid name, location and budget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvAELehwbsJnhUC96TkKgw.png" /><figcaption>example unit test for a success case in tests/createRestaurant.test.js</figcaption></figure><p>Here is the our test file with it’s first test! If any of the three except() fail, then the test will fail and we will know something in our function is broken. For now, let’s run the test and see if it will work.</p><h3><strong>Step 7. Running Tests</strong></h3><p>In your package.json , add a test script:</p><pre>&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;jest --testEnvironment=node --runInBand ./tests&quot;<br>}</pre><p>The --runInBand is there to get the tests to run one after another.</p><p>The --testEnvironment=node is there as we’re in a node environment.</p><p>What’s really important here is to give the correct file path to your test folder. For me that was ./tests .</p><p>Now when you run npm test in the terminal, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hh-Eh1nAd4EKEntb8ATNw.png" /><figcaption>Successful jest test</figcaption></figure><p>Now this was an example of a success test case. I will show you how to write tests for errors.</p><h4><strong>Error Testing</strong></h4><p>In the same file, you can create a new describe block for cases where we fail to create a new restaurant. Looking back at our Schema and function, the only times it should fail is if a name has been repeated or if the cost associated with a restaurant is not one of the values in the enum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqzW9RMU1ul6v4Pz-TS3Mg.png" /><figcaption>example testing for exceptions in tests/createRestaurant.js</figcaption></figure><p>In the first test, we’re checking that an error will be thrown if a name is repeated. We have already tested for the case of one restaurant being made successfully so we can be rest assured that line 33 will run smoothly.</p><p>However, line 35 should throw an error since the name “First” already belongs to another restaurant. As this is an asynchronous function that is meant to throw an error, we need to add rejects.toThrow() after our expect.</p><p>In the second test, we’re checking that an error is thrown when the third argument of createRestaurant() is not a string value in the cost enum.</p><p>If you run your tests again you should see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*je3wMbG_KA0BoRo8iJkIpQ.png" /><figcaption>Running all tests successfully</figcaption></figure><p>Congratulations! You have successfully unit tested your Node.js and Mongoose backend using Jest.</p><p>Thanks for reading and please leave a comment if you’re unsure about anything. This is my first article so chances are I’ve not done a perfect job so please let me know if you spot any problems 😌</p><p>If you want to do more with jest like using <strong>mocks</strong> to ‘mock’ the behaviour of external functions, read <a href="https://yasaminkamali.medium.com/jest-mock-for-unit-testing-mern-backend-983c1e3fef83">this blog </a>🥳</p><h3>References</h3><p><a href="https://dev.to/paulasantamaria/testing-node-js-mongoose-with-an-in-memory-database-32np">https://dev.to/paulasantamaria/testing-node-js-mongoose-with-an-in-memory-database-32np</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106a39b8393d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/unit-testing-node-js-mongoose-using-jest-106a39b8393d">Unit Testing Node.js + Mongoose Using Jest</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>