<?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 Kavian Rabbani on Medium]]></title>
        <description><![CDATA[Stories by Kavian Rabbani on Medium]]></description>
        <link>https://medium.com/@kavianrabbani?source=rss-e93532ada85a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2zl4xeCRQp8yBWQPd2E74w.jpeg</url>
            <title>Stories by Kavian Rabbani on Medium</title>
            <link>https://medium.com/@kavianrabbani?source=rss-e93532ada85a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:30:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kavianrabbani/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[The Hidden Danger of Hardcoded data-testid in Testing]]></title>
            <link>https://medium.com/@kavianrabbani/the-hidden-danger-of-hardcoded-data-testid-in-testing-8ec9e671955e?source=rss-e93532ada85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec9e671955e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Kavian Rabbani]]></dc:creator>
            <pubDate>Wed, 08 Feb 2023 16:36:07 GMT</pubDate>
            <atom:updated>2023-02-13T09:08:28.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Avoid Hard Coding data-testid</h3><h3>A Guide to Avoiding False Positives</h3><p>When building a web application, you need to ensure that your components are well-tested. One of the ways to test your application is to use a library like <a href="https://testing-library.com/docs/">@testing-library</a>. This library provides you with functions to render your components and interact with them, making it easier to test your app.</p><figure><img alt="Caution" src="https://cdn-images-1.medium.com/max/1024/0*SwSG5l2fF1Ic2NHt" /><figcaption>Photo by <a href="https://unsplash.com/@gohrhyyan?utm_source=medium&amp;utm_medium=referral">Goh Rhy Yan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the key elements in making your components testable is to add unique data-testid attributes to them. These attributes act as selectors that help the testing library identify the components you want to test. However, it’s important to avoid hardcoding these attributes in your components, as doing so might lead to <a href="https://en.wikipedia.org/wiki/False_positives_and_false_negatives#False_positive_error">false positives</a> when testing your app.</p><p>Here’s an example of a hardcoded data-testid:</p><pre>import React from &#39;react&#39;;<br><br>interface ButtonProps {<br>  label: string;<br>  onClick: () =&gt; void;<br>}<br><br>const Button: React.FC&lt;ButtonProps&gt; = ({ label, onClick }) =&gt; {<br>  return (<br>    &lt;button data-testid=&quot;submit-button&quot; onClick={onClick}&gt;<br>      {label}<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><p>Let’s test if it’s working as expected:</p><pre>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react&#39;;<br>import Button from &#39;./Button&#39;;<br><br>describe(&#39;Button component&#39;, () =&gt; {<br>  it(&#39;should call onClick function when button is clicked&#39;, () =&gt; {<br>    const mockOnClick = jest.fn();<br>    const { getByTestId } = render(<br>      &lt;Button label=&quot;Submit&quot; onClick={mockOnClick} /&gt;<br>    );<br>    const submitButton = getByTestId(&#39;submit-button&#39;);<br>    fireEvent.click(submitButton);<br>    expect(mockOnClick).toHaveBeenCalled();<br>  });<br>});</pre><p>As you can see, the test passes, <strong>but</strong> if you have multiple instances of this component on a page, the hardcoded data-testid will lead to incorrect test results.</p><p>Hardcoding data-testid attributes in reusable components might lead to <a href="https://en.wikipedia.org/wiki/False_positives_and_false_negatives#False_positive_error">false positives</a> when testing your app. Take a look at this example:</p><pre><br>import React from &#39;react&#39;;<br><br>interface ButtonProps {<br>  label: string;<br>  onClick: () =&gt; void;<br>}<br><br>const Button: React.FC&lt;ButtonProps&gt; = ({ label, onClick }) =&gt; {<br>  return (<br>    &lt;button data-testid=&quot;submit-button&quot; onClick={onClick}&gt;<br>      {label}<br>    &lt;/button&gt;<br>  );<br>};<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Button label=&quot;Submit 1&quot; onClick={() =&gt; console.log(&#39;Button 1 clicked&#39;)} /&gt;<br>      &lt;Button label=&quot;Submit 2&quot; onClick={() =&gt; console.log(&#39;Button 2 clicked&#39;)} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>Now, let’s write a test for this App component, where we want to check if both buttons are working as expected:</p><pre>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react&#39;;<br>import App from &#39;./App&#39;;<br><br>describe(&#39;App component&#39;, () =&gt; {<br>  it(&#39;should call the onClick function of both buttons when they are clicked&#39;, () =&gt; {<br>    const mockOnClick1 = jest.fn();<br>    const mockOnClick2 = jest.fn();<br>    const { getByTestId } = render(<br>      &lt;App /&gt;<br>    );<br>    const submitButton1 = getByTestId(&#39;submit-button&#39;);<br>    fireEvent.click(submitButton1);<br>    expect(mockOnClick1).toHaveBeenCalled();<br>    const submitButton2 = getByTestId(&#39;submit-button&#39;);<br>    fireEvent.click(submitButton2);<br>    expect(mockOnClick2).toHaveBeenCalled();<br>  });<br>});</pre><p>In this case, even though we are using different onClick functions for both buttons, the test <strong>will still pass</strong>, because both buttons have the same data-testid of submit-button. This is a clear example of how hardcoded testids can lead to <a href="https://en.wikipedia.org/wiki/False_positives_and_false_negatives#False_positive_error">false positives</a> in testing.</p><p>To avoid this issue, you should pass data-testid attributes as props, so each component instance can have a unique value. This will help ensure that your tests are accurate and reliable. Here’s an example:</p><pre>import React from &#39;react&#39;;<br><br>interface ButtonProps {<br>  label: string;<br>  onClick: () =&gt; void;<br>  testId: string;<br>}<br><br>const Button: React.FC&lt;ButtonProps&gt; = ({ label, onClick, testId }) =&gt; {<br>  return (<br>    &lt;button data-testid={testId} onClick={onClick}&gt;<br>      {label}<br>    &lt;/button&gt;<br>  );<br>};<br><br>export default Button;</pre><p>And here’s the updated test for this component:</p><pre>import React from &#39;react&#39;;<br>import { render, fireEvent } from &#39;@testing-library/react&#39;;<br>import Button from &#39;./Button&#39;;<br><br>describe(&#39;Button component&#39;, () =&gt; {<br>  it(&#39;should call onClick function when button is clicked&#39;, () =&gt; {<br>    const mockOnClick = jest.fn();<br>    const { getByTestId } = render(<br>      &lt;Button label=&quot;Submit&quot; onClick={mockOnClick} testId=&quot;submit-button-1&quot; /&gt;<br>    );<br>    const submitButton = getByTestId(&#39;submit-button-1&#39;);<br>    fireEvent.click(submitButton);<br>    expect(mockOnClick).toHaveBeenCalled();<br>  });<br>});</pre><p>With this approach, you can render multiple instances of the component and each instance will have a unique testid, allowing you to test each component instance individually.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec9e671955e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn “this” Keyword, Once and Forever]]></title>
            <link>https://medium.com/@kavianrabbani/learn-this-keyword-once-and-forever-81c59ec805ba?source=rss-e93532ada85a------2</link>
            <guid isPermaLink="false">https://medium.com/p/81c59ec805ba</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kavian Rabbani]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 19:07:13 GMT</pubDate>
            <atom:updated>2024-12-30T13:47:50.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learn Javascript “this”, Once and Forever</h3><p>As a javascript developer, whether you are writing vanilla(pure) js, creating the next “React” yourself, or working with Vue, Angular, Svelte, or any other framework/library, you need to know this well.</p><p>As I talk to other developers, I sometimes notice that there is a big hole in their understanding of this. so I’m here to mention some of them and make you and this good friends forever :)</p><figure><img alt="You got this" src="https://cdn-images-1.medium.com/max/1024/0*lsvm_OdetGWo6Rbz" /><figcaption>Photo by <a href="https://unsplash.com/@prateekkatyal?utm_source=medium&amp;utm_medium=referral">Prateek Katyal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s dive into some examples to start learning what this is and how it’s used.</p><pre>function logThis() {<br>  console.log(this);<br>}</pre><p>Assume we wrote logThis.<br>What if we call it? what is the value of this?<br>So, the truth is, it depends :) like any other question.<br>on what? let me explain:<br>we can call a function in a number of ways,</p><p>1- Invoking it normally, like logThis(),<br>2- Set it as a method of an object and then call it like obj.logThis(),<br>3- With the use of .call, .apply or .bind<br>4- And finally, calling it with new, like new LogThis().</p><p>Here is a rule of thumb:<strong><br>How you call a function determines what </strong><strong>this is.</strong></p><p>Let’s discuss it further.</p><p>1- normal invocation with ()<br>in this case, the answer is global object, which is window in Browser global in Node. just to mention, there is a subtle point. if we’re in strict mode the answer to example 1, is always undefined.</p><p>Let’s go to the next case,</p><p>2- calling a function as a method of an object, x.y()</p><pre>function logThis() {<br>  console.log(this);<br>}<br><br>const obj = {<br>  value: 20,<br>  logMyThis: logThis,<br>}<br><br>const obj2 = {<br>  value: 30,<br>  logMyThis: function() {<br>    console.log(this);<br>  }<br>}<br><br>obj.logMyThis();   // obj<br>obj2.logMyThis();  // obj2</pre><p>See? There is no difference between the results above.<br>It’s all about how we <strong>call</strong> each function.</p><p>As we can see in the example above, there is no difference in how we assigned the method to our objects. the value of this depends on how we call that function, nothing more. when we call a function like x.y.z(), this will be x.y.</p><p>You might ask what if we have a method in an obj, and then we assign it to a variable and then call that new function?</p><pre>const obj = {<br>  value: 30,<br>  logMyThis: function() {<br>    console.log(this);<br>  }<br>}<br><br>const logThis2 = obj.logMyThis;<br><br>logThis2();      // global object (window in browser)<br>obj.logMyThis(); // obj</pre><p>It’s trivial where the function originally belongs, actually.<br>All that’s important is how we <strong>invoke/call</strong> it.</p><p>As you see, the thing is “all that’s important, is that <strong>how function calls are written</strong>”.</p><p>3- Using call, apply orbind</p><p>generally speaking, bind, call, and apply are used to change the this of function. The context that a function will have when it’s running.<br>but there is a subtle difference between bind and call/apply.<br>bindreturns a new function, with the this that we set; whereas, call and apply do not return a new function. Instead, they <strong>call</strong> the original function with our desired this.<br>Now we know how call, apply, and bind work.<br>Let’s talk about this in each one.</p><pre>function setValueAndLogThis(value) {<br>  this.value = value;<br>  console.log(this);<br>}<br><br>const myThis = {<br>  value: 20,<br>}<br><br>setValueAndLogThis(30);<br>// window with window.value set to 30<br><br>setValueAndLogThis.call(myThis, 40);<br>// sets the value of myThis to 40 and logs myThis<br><br>setValueAndLogThis.apply(myThis, [50]);<br>// sets the value of myThis to 50 and logs myThis<br><br>const newLogger = setValueAndLogThis.bind(myThis);<br>// setValueAndLogThis is not called<br>// However, we have a new copy of setValueAndLogThis<br>// with a hard-set `this` value (myThis) bound to it<br><br>newLogger(60);<br>// sets the value of myThis to 60 and logs it<br><br>console.log(myThis.value); // 60</pre><p>As we can see, we can change the context of a function both when we want to call it immediately(by call and apply), and when we want to call it later(by bind).<br>Keep in mind that whenever we use bind, we are creating a function that we never can change it’s this, expect when we call this function by new</p><p>4- And finally, calling a function withnew</p><p>The new keyword is a strong one. it rules over all of the above cases when we are talking about this.<br>Whenever a function is called with new, regardless of how it’s written, the function starts to run with a this equal to an empty object.<br>if we don’t return this, it’s returned automatically. but another point is that if we return any <strong>object</strong> other than this, then this will not get returned and that object will, instead. any primitive value (like string, number, null, …) returned, will be ignored and will result to this being returned.</p><p>By now, you know everything about this when we are working with a normal function. but wait :)<br>there is more to learn.</p><p>Things go to change a little when we talk about <strong>arrow functions</strong>.<br>First, we should know that an arrow function could not be called as a constructor function(with new operator).<br>The second point is that we can never change this value of an arrow function. even by creating a new one with the help of bind.<br>And the third, last, and most important point is that the value of this for an arrow function is not determined by <strong>How we call it</strong> but is determined by <strong><em>Where</em> we declare it <em>first*</em>.</strong></p><p>there are two important words above: <strong>Where</strong> and <strong>First.</strong></p><p>by “where”, I mean the function scope (not to be confused with an object or block scope) in which we are creating that arrow function. let’s see an example:</p><pre>const obj = {<br>  value: 20,<br>  logMyThis: () =&gt; {<br>    console.log(this);<br>  }<br>}<br><br>obj.logMyThis(); // global object (window in browsers)</pre><p>when logMyThis method was being declared, the main function of the app was running with this value of window or global. so when javascript interpreter looks at this arrow function expression, it basically behaves like the below:</p><pre>const obj = {<br>  value: 20,<br>  logMyThis: (function () {<br>    console.log(this);<br>  }).bind(this)<br>}</pre><p>It creates a new function bound to the this in the main function(that is global object).<br>Let’s talk about a more complex example:</p><pre>function runInnerArrowFunction() {<br>  const obj = {<br>    value: 20,<br>    logMyThis: () =&gt; {<br>      console.log(this);<br>    }<br>  }<br><br>  obj.logMyThis();<br>}<br><br>runInnerArrowFunction();</pre><p>As we learned in the very first example, by invoking runInnerArrowFunction this way, we are implicitly setting its this value equal to window.<br>Then, it declares/defines a variable/object within itself.<br>And consequently, creates a method inside of it just like below:</p><pre>const obj = {<br>  value: 20,<br>  logMyThis: (function() {<br>    console.log(this)<br>  }).bind(this);<br>}</pre><p>Therefore, it logs window object.<br>And one step further:</p><pre>const customThis = { value: 20 };<br>runInnerArrowFunction.call(customThis); // customThis</pre><p>Now, you know that the way we call runInnerArrowFunction is determining the value of this for the inner arrow function.</p><p>Now, let’s discuss the second important word: <strong>First<br></strong>take a look at the example below:</p><pre>const obj = {<br>  value: 20,<br>  logMyThis: () =&gt; {<br>    console.log(this);<br>  }<br>}<br><br>// The this value of `logMyThis` is already bound to it<br>// as `obj` and `obj.logMyThis` were being declared/defined above.<br>// `this` will be be undefined in strict mode and<br>// will reference to the global object in non-strict mode.<br><br>function runOuterArrowFunction() {<br>  const logThis = obj.logMyThis;<br>  logThis();<br>}<br><br>runOuterArrowFunction(); // window<br>runOuterArrowFunction.call({ value: 100 }) // window<br></pre><p>As you can see there is no difference in <strong>How</strong> we call the function. Once this is bound, it will stay bound, forever. Remember, it’s one of the characteristics of arrow functions (not all functions).</p><p>If you found this post useful and enjoyed reading it, please don’t forget to clap :) and leave a comment below. it’s my first post and I am looking forward to getting feedback as much as possible.</p><p>Also if you think that there is something wrong with this post, please let me know.</p><p>Cheers! 🍻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81c59ec805ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>