<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Programming Archives - Yumasoft</title>
	<atom:link href="https://blog.yumasoft.pl/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.yumasoft.pl/category/programming/</link>
	<description>Software development blog</description>
	<lastBuildDate>Wed, 24 Nov 2021 02:06:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.yumasoft.pl/wp-content/uploads/2021/05/cropped-yumasoft_icon_transparent-32x32.png</url>
	<title>Programming Archives - Yumasoft</title>
	<link>https://blog.yumasoft.pl/category/programming/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Webpack Watch Cached And Not Refreshing Bundles</title>
		<link>https://blog.yumasoft.pl/2021/11/webpack-watch-cached-and-not-refreshing-bundles/</link>
					<comments>https://blog.yumasoft.pl/2021/11/webpack-watch-cached-and-not-refreshing-bundles/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 24 Nov 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[webpack]]></category>
		<category><![CDATA[webpack watch]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=829</guid>

					<description><![CDATA[<p>If you use webpack as your JavaScript bundler, you might have experienced an issue with webpack --watch not refreshing your bundles when modifying the source files. In this case, webpack&#8217;s output after changing the file is similar to the following one: As you can see, there are some [cached] mentions there in a few places&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/11/webpack-watch-cached-and-not-refreshing-bundles/">Webpack Watch Cached And Not Refreshing Bundles</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you use <a href="https://webpack.js.org/">webpack</a> as your JavaScript bundler, you might have experienced an issue with <code>webpack --watch</code> not refreshing your bundles when modifying the source files. In this case, webpack&#8217;s output after changing the file is similar to the following one:</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="87" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchNotRefreshingCache-1024x87.png" alt="Webpack output showing [cached]" class="wp-image-830" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchNotRefreshingCache-1024x87.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchNotRefreshingCache-300x25.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchNotRefreshingCache-768x65.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchNotRefreshingCache.png 1112w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>As you can see, there are some <code>[cached]</code> mentions there in a few places and no <code>[code generated]</code> statements at all. The effect is that your bundles are not rebuilt at all. In order to have them refreshed, you need to restart the building process, which takes time and makes your development flow painful. If you want to know how to solve that problem, read on ?</p>



<span id="more-829"></span>



<h2 class="wp-block-heading">webpack watch cached files</h2>



<p>We have struggled with this issue for quite some time. It starts with launching <code>webpack</code> with <code>--watch</code> option. Such build script can be defined in your <code>package.json</code> in the following or similar way:</p>



<script src="https://gist.github.com/dsibinski/974e74538fae860a5d1f908b8193fcd4.js"></script>



<p>The effect you would expect is for webpack to rebuild your bundles as soon as you make any change in the source code.</p>



<p>When the webpack watch cached issue occurs, the first change you make in a file is properly reloaded by <code>webpack</code> and looks similarly to that:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="375" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchCorrectRefreshFirstTime-1024x375.png" alt="webpack watch correctly rebuilding bundles with [code generated] statements" class="wp-image-832" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchCorrectRefreshFirstTime-1024x375.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchCorrectRefreshFirstTime-300x110.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchCorrectRefreshFirstTime-768x281.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/2_WebpackWatchCorrectRefreshFirstTime.png 1048w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>However, as soon as you change the file for the second time, the output looks less promising:</p>



<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="87" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/1_WebpackWatchNotRefreshingCache-1024x87.png" alt="webpack watch cached issue" class="wp-image-833" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/1_WebpackWatchNotRefreshingCache-1024x87.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/1_WebpackWatchNotRefreshingCache-300x25.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/1_WebpackWatchNotRefreshingCache-768x65.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/1_WebpackWatchNotRefreshingCache.png 1112w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>As soon as you see some of these <code>[cached]</code> things, it probably means that webpack cached something and did not generate new bundles. Especially if there are no <code>[built]</code> and <code>[code generated]</code> statements in the output. You notice that your files are not refreshed, so your last change is not reflected in JS bundles ?</p>



<h2 class="wp-block-heading">Hotfix: disable webpack cache</h2>



<p>The first hotfix solution &#8211; especially if you can&#8217;t easily find the cause &#8211; is to disable <code>webpack</code> cache completely. In order to do that, you should set <code>cache</code> to <code>false</code> in your <a href="https://webpack.js.org/configuration/cache/">webpack configuration file</a>:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="413" height="216" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/3_WebpackDisableCache.png" alt="cache set to false in webpack config file" class="wp-image-836" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/3_WebpackDisableCache.png 413w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/3_WebpackDisableCache-300x157.png 300w" sizes="auto, (max-width: 413px) 100vw, 413px" /></figure></div>



<p>This will work, and webpack should now rebuild your bundles on every source change. However, it comes with a significant performance cost. Disabling the cache will make webpack actually rebuilding all your bundles on each change. This solution is actually a shortcut for restarting the build from scratch. Not what we really want ? Let&#8217;s see how to find the cause and solve webpack watch cached issue properly.</p>



<h2 class="wp-block-heading">Wrong casing &#8211; the real cause of webpack watch cached issue</h2>



<p>In our case, the problem turned out to basically be <strong>wrong casing when importing stuff</strong>. </p>



<p>The general advice is to find how given file you are modifying is entered into your webpack&#8217;s build flow. It can be <a href="https://flexiple.com/javascript-require-vs-import/">imported or required</a> directly. Maybe it&#8217;s used via <a href="https://webpack.js.org/configuration/resolve/">webpack alias</a>. I know these are quite general statements, so I&#8217;ll show you two examples.</p>



<h3 class="wp-block-heading">Wrong casing in import</h3>



<p>First, we had a problem of <code>webpack watch</code> not refreshing bundles after making changes in a single file. This file is named <code>questionnaireCorrectTemplate.tsx</code>. It exports a single React component called <code>QuestionnaireCorrectTemplate</code>.</p>



<p>In order to use this component, we imported it in another file in the following way:</p>



<script src="https://gist.github.com/dsibinski/a3e267ad6a41defc62fa22b405f8f96a.js"></script>



<p>Have you already noticed the problem? Note that the import contains the module name with <strong>capital</strong> letter: &#8220;./<strong>Q</strong>uestionnaireCorrectTemplate&#8221;. As soon as we changed it to a small letter, so exactly as the  <code>questionnaireCorrectTemplate.tsx</code>  file&#8217;s name:</p>



<script src="https://gist.github.com/dsibinski/af26050bee05f9c52a5a253326b801a6.js"></script>



<p>Everything started to magically work ? Since this change, <code>webpack watch</code> is properly rebuilding our bundles after changes in the affected file ?</p>



<h3 class="wp-block-heading">Wrong casing in webpack alias</h3>



<p>We had another issue with <code>webpack</code> not refreshing the bundles when we made changes in a <code>Site.css</code> file. This is a file in which we store custom CSS for our React app. The issue was very similar to the previous one. After starting <code>webpack watch</code>, the first modification of <code>Site.css</code> file triggered a proper rebuild of bundles:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="315" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/4_WebpackCssCorrectRefresh-1024x315.png" alt="webpack watch correctly rebuilding bundles for css file" class="wp-image-840" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/4_WebpackCssCorrectRefresh-1024x315.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/4_WebpackCssCorrectRefresh-300x92.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/4_WebpackCssCorrectRefresh-768x236.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/4_WebpackCssCorrectRefresh.png 1114w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>However, all subsequent modifications to the <code>Site.css</code> file causes the webpack watch cached issue:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="1024" height="66" src="https://blog.yumasoft.pl/wp-content/uploads/2021/11/5_WebpackCachedCssIssue-1024x66.png" alt="webpack watch cached issue for css file" class="wp-image-841" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/11/5_WebpackCachedCssIssue-1024x66.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/5_WebpackCachedCssIssue-300x19.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/5_WebpackCachedCssIssue-768x50.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/11/5_WebpackCachedCssIssue.png 1094w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure>



<p>The reason was wrong casing again. However, this time we found out that the <code>Site.css</code> file was included as an alias in webpack configuration file:</p>



<script src="https://gist.github.com/dsibinski/731c30adc2b09ac12120a8426be5b400.js"></script>



<p>I guess you can already see what is the problem ? The file was included as <code><strong>s</strong>ite.css</code>, instead of <code><strong>S</strong>ite.css</code>. As soon as we changed this part of the <code>webpack.config.js</code> file to the one with proper casing:</p>



<script src="https://gist.github.com/dsibinski/2d9900d68441aa83e50584d0ac2b91a8.js"></script>



<p>Everything started to work correctly. Since this change, <code>webpack watch</code> correctly refreshes the bundles after each modification of <code>Site.css</code> file ?</p>



<h2 class="wp-block-heading">Webpack watch cached &#8211; summary</h2>



<p>I hope this article helps you solve your <code>webpack watch</code> refreshing issue ? Webpack is still kind of magical tool for me and it surprises me very often. Such issues can be really painful &#8211; that&#8217;s why I wanted to share our solution to this problem with you. </p>



<p>The general advice is to find how the problematic file is imported/required/added to webpack build flow. It&#8217;s very probably that you have the wrong casing somewhere. I hope it saves you some pain one day!</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/11/webpack-watch-cached-and-not-refreshing-bundles/">Webpack Watch Cached And Not Refreshing Bundles</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/11/webpack-watch-cached-and-not-refreshing-bundles/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How Does TypeScript Types Narrowing Work?</title>
		<link>https://blog.yumasoft.pl/2021/10/how-does-typescript-types-narrowing-work/</link>
					<comments>https://blog.yumasoft.pl/2021/10/how-does-typescript-types-narrowing-work/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 27 Oct 2021 05:30:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ts]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=736</guid>

					<description><![CDATA[<p>Have you ever heard about TypeScript types narrowing? Have you ever seen such an error in your TypeScript code: Even tough, you really knew that the name property exists on the person object? How did you solve this problem? Did you cast the variable to the expected type? If the answer to at least one&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/10/how-does-typescript-types-narrowing-work/">How Does TypeScript Types Narrowing Work?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Have you ever heard about <em>TypeScript types narrowing</em>? Have you ever seen such an error in your TypeScript code:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="604" height="118" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_missing_property_error.png" alt="TypeScript complains about &quot;name&quot; property not existing  on &quot;person&quot; object of type &quot;object&quot;" class="wp-image-746" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_missing_property_error.png 604w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_missing_property_error-300x59.png 300w" sizes="auto, (max-width: 604px) 100vw, 604px" /></figure></div>



<p>Even tough, you <em>really knew</em> that the <code>name</code> property exists on the <code>person</code> object? How did you solve this problem? Did you cast the variable to the expected type?</p>



<p>If the answer to at least one of those questions is <em>yes,</em> you might read on. There are better ways of determining the type of local variable in TypeScript. What&#8217;s more, TS compiler does a lot of stuff for us by leveraging types narrowing. In this article, we are going to see how it works and how it can be useful ?</p>



<span id="more-736"></span>



<h2 class="wp-block-heading">TypeScript types narrowing &#8211; what is that?</h2>



<p>One of the <a href="https://blog.yumasoft.pl/2021/06/migrating-javascript-react-app-to-typescript/">goals of TypeScript</a> is to make writing JavaScript code better and more secure by adding the typing system. However, we don&#8217;t want the typing system to be problematic and making us to use the <em>dirty haxes</em> like all the time casting our variables explicitly, do we? ?</p>



<p>First, we need to understand that TypeScript does a lot of stuff in order to ensure we work with the most specific type as possible. Basically, if the exact type of local variable can be determined, TS compiler tries to do that.</p>



<p>Imagine such a function:</p>



<script src="https://gist.github.com/dsibinski/b67234dc1fa7fba52a0695ce8b001c4d.js"></script>



<p>In <a href="https://www.javatpoint.com/what-is-vanilla-javascript">vanilla JS</a>, such code would of course compile. But in our case, TypeScript sees a problem:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="730" height="170" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_type_error.png" alt="TypeScript complains that &quot;lenght&quot; doesn't exist on a variable of type &quot;string&quot; or &quot;number&quot;" class="wp-image-740" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_type_error.png 730w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/1_TypeScript_type_error-300x70.png 300w" sizes="auto, (max-width: 730px) 100vw, 730px" /></figure></div>



<p>The compiler is right here. Our parameter is either <code>string</code> or <code>number</code>, so the <code>length</code> property may not be available if someone passes a <code>number</code>.</p>



<p>You might have already been in such situations. What did you do? Well, sometimes when the code is more complex, and you <em>just know</em> that the variable contains the requested property, it might be tempting to cast:</p>



<script src="https://gist.github.com/dsibinski/fe0787bacfdadb10e0411c126a85f978.js"></script>



<p>Of course, we will satisfy the compiler here. But does that make our code any more safe than the previous version? Not at all.</p>



<p>In our example, based on the code we have written, TypeScript is not able to determine the exact type of <code>variable</code>. We can help it by using <em>type guards</em>. We will talk about them in details in a separate article. However, for now it&#8217;s enough to know that the language has some built-in type guards &#8211; one of them is <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#typeof-type-guards">typeof</a>. Let&#8217;s use it in our function:</p>



<script src="https://gist.github.com/dsibinski/3848759ec400644ce6b36326cb5b3e13.js"></script>



<p>That&#8217;s cool, TS compiler doesn&#8217;t complain anymore. But how does it work? Our code is still accessing <code>variable.length</code> directly, there&#8217;s no casting there.</p>



<p>Notice what your IDE tells you when you hover your mouse over the <code>variable</code> in the first <em>if</em> branch after checking if the type is <code>string</code>:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="559" height="202" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/2_TypeScript_narrowing1.png" alt="TypeScript types narrowing figures out the type of variable is &quot;string&quot;" class="wp-image-741" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/2_TypeScript_narrowing1.png 559w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/2_TypeScript_narrowing1-300x108.png 300w" sizes="auto, (max-width: 559px) 100vw, 559px" /></figure></div>



<p>and also what it tells you when hovering over <code>variable</code> in the <code>else</code> block:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="560" height="178" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/3_TypeScript_narrowing2-1.png" alt="TypeScript types narrowing figures out the type of variable is &quot;number&quot;" class="wp-image-743" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/3_TypeScript_narrowing2-1.png 560w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/3_TypeScript_narrowing2-1-300x95.png 300w" sizes="auto, (max-width: 560px) 100vw, 560px" /></figure></div>



<p>Wow! The IDE magically knows what&#8217;s the exact type of our locally scoped variable! ?</p>



<p>This magic is called <em>types narrowing</em>. TypeScript compiler does many things to ensure that the type of local variable you work with is of the most specific type possible. It is based on the complex analysis of the source code, especially the code surrounding the place in which the local variable is used.</p>



<h2 class="wp-block-heading"><em>in</em> keyword in types narrowing</h2>



<p>Let&#8217;s take a look at this code now:</p>



<script src="https://gist.github.com/dsibinski/5ecdd052adb538e50e3f4917d11fe785.js"></script>



<p>Let&#8217;s say we have a variable which may either be <code>Employee</code> or <code>Manager</code>:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="166" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/5_TypeScript_narrowing_unknown_type-1-1024x166.png" alt="TypeScript doesn't know the type is it's not narrowed" class="wp-image-756" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/5_TypeScript_narrowing_unknown_type-1-1024x166.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/5_TypeScript_narrowing_unknown_type-1-300x49.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/5_TypeScript_narrowing_unknown_type-1-768x125.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/5_TypeScript_narrowing_unknown_type-1.png 1189w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>In that place, TypeScript can&#8217;t say whether <code>person</code> is <code>Employee</code> or <code>Manager</code>.</p>



<p>Maybe you&#8217;ve used the <code>in</code> keyword for determining types before. Types narrowing also works with <code>in</code> keyword:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="688" height="228" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/6_TypeScript_narrowing_in_keyword.png" alt="in keyword helps TypeScript narrow the type" class="wp-image-757" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/6_TypeScript_narrowing_in_keyword.png 688w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/6_TypeScript_narrowing_in_keyword-300x99.png 300w" sizes="auto, (max-width: 688px) 100vw, 688px" /></figure></div>



<p>As you can see, TypeScript analyzed the flow, and it noticed that in the first <code>if</code> block we check whether the <code>person</code> object contains the <code>employees</code> property. If it does, the compiler known it must be <code>Manager</code>, not <code>Employee</code>. Cool, isn&#8217;t it? ?</p>



<h2 class="wp-block-heading">Narrowing and equality operator</h2>



<p>Another interesting application of TypeScript types narrowing is using the equality operator:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="780" height="417" src="https://blog.yumasoft.pl/wp-content/uploads/2021/10/7_TypeScript_narrowing_equality.png" alt="TypeScript types narrowing determines type of variable based on === equality operator" class="wp-image-760" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/10/7_TypeScript_narrowing_equality.png 780w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/7_TypeScript_narrowing_equality-300x160.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/10/7_TypeScript_narrowing_equality-768x411.png 768w" sizes="auto, (max-width: 780px) 100vw, 780px" /></figure></div>



<p>Notice how TypeScript determines the type of variables based on the <code>===</code> operator. If both parameters are equal, they must be both <code>string</code>s.</p>



<h2 class="wp-block-heading">TypeScript types narrowing &#8211; summary</h2>



<p>Narrowing in TypeScript is a very power feature of the language. I just showed you some simple examples, so you can grasp the idea and notice how much TS compiler does to ensure your type is <em>the correct one</em>.</p>



<p>If you&#8217;re interested, you can read much more about this in <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html">TypeScript docs</a>. It&#8217;s however worth knowing how TypeScript compiler works and how you should properly check for types in your code. Remember that using <code>any</code> or explicit casting should be your last resort ?</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/10/how-does-typescript-types-narrowing-work/">How Does TypeScript Types Narrowing Work?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/10/how-does-typescript-types-narrowing-work/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>When Not To Use TDD?</title>
		<link>https://blog.yumasoft.pl/2021/10/when-not-to-use-tdd/</link>
					<comments>https://blog.yumasoft.pl/2021/10/when-not-to-use-tdd/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Thu, 21 Oct 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[test driven development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=719</guid>

					<description><![CDATA[<p>Some time ago we talked about 7 reasons to start using Test Driven Development. As soon as you learn it and start practicing it on a daily basis, it might be tempting to always be TDDing. However, TDD is not always a good fit. There are some cases when it might not be worth using&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/10/when-not-to-use-tdd/">When Not To Use TDD?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Some time ago we talked about <a href="https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/">7 reasons to start using Test Driven Development</a>. As soon as you learn it and start practicing it on a daily basis, it might be tempting to always be <em>TDDing</em>. However, TDD is not always a good fit. There are some cases when it might not be worth using TDD. Let&#8217;s explore them today ?</p>



<span id="more-719"></span>



<h2 class="wp-block-heading">Prototypes</h2>



<p>You may consider not doing TDD with prototypes. By <em>prototype</em>, I mean an app that will most probably be thrown away or completely changed very soon. It may be created when you are experimenting with some technology/framework or are just asked to <em>conduct research</em> on something.</p>



<p>TDD gives you a high code/flow coverage, which may need to be changed in case of prototype projects. If you are in such situation, consider resigning from TDD at this stage.</p>



<h2 class="wp-block-heading">Short living apps</h2>



<p>Similarly to prototypes, short living solutions might be the ones where TDD is not the best fit. It applies to one-time-use apps or scripts which are supposed to do one thing well and quickly.</p>



<p>Short living apps are the ones where you may consider not using Test Driven Development. I&#8217;d even argue whether you need any kind of tests for such programs. Testing such apps or even scripts may be art for art&#8217;s sake. If something is supposed to realize a given task without fireworks (like reusability, maintenance etc.), I wouldn&#8217;t bother with testing it. It&#8217;s better to focus on solving your current, short-lived problem than on practicing the profound TDD idea ?</p>



<h2 class="wp-block-heading">Unclear requirements</h2>



<p>One of the reasons not to use TDD might be unclear requirements. The idea of writing tests in Test Driven Development is to define the expected outcomes for predefined incomes. As we said <a href="https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/">in the previous article</a>, Test Driven Development can help spot the edge cases and make the business requirements more <em>close to the code</em>. However, if you don&#8217;t have these requirements defined, TDD might be a waste of time (at this stage). If the requirements actually arrive or are completely changed, your significant set of tests will need to be changed or even removed.</p>



<h2 class="wp-block-heading">MVP</h2>



<p>If you&#8217;re creating an <a href="https://en.wikipedia.org/wiki/Minimum_viable_product">MVP</a>, with very short time and budget, TDD might not be worth the struggle. It&#8217;s probably better to resign from using TDD in that case. You should rather focus on your product and the business value it needs to deliver. TDD might slow down the delivery time, which, in case of MVPs, can be critical. It&#8217;s better to deliver the minimum viable product without TDD than to not deliver it with TDD ?</p>



<p>However, remember to add some tests, even post-factum. MVPs have a high chance of survival, so you&#8217;d want your final product to be tested and testable. You need to find a good balance here, not to make your solution completely untestable when it&#8217;s ready for production use.</p>



<h2 class="wp-block-heading">Tests writing beginner</h2>



<p>If you are a total beginner in writing tests in general, Test Driven Development might not be the best approach to start with. You may consider not to use TDD at the beginning of your testing journey.</p>



<p>To make Test Driven Development effective, you should be able to write tests quickly and efficiently. Starting to learn software testing with Test Driven Development may make you feel overwhelmed and discouraged. If you&#8217;re a beginner, I suggest to first write some unit tests, get familiar with that and then try to learn Test Driven Development. </p>



<p>It would be great if you can find some smaller and well-defined task to start with TDD. If you don&#8217;t have such tasks, try solving one of the programming katas (e.g. <a href="https://codingdojo.org/kata/StringCalculator/">this one</a>) with TDD. </p>



<h2 class="wp-block-heading">When not to use TDD &#8211; summary</h2>



<p>Like everything, TDD is not a gold standard for every possible case. It should be used as often as possible, but not always. Remember to always weight the gains and losses from using Test Driven Development in a given project or application at a given time.</p>



<p>What&#8217;s your experience with Test Driven Development? Can you list any more cases where it&#8217;s not worth using it? Share your thoughts in the comments below!</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/10/when-not-to-use-tdd/">When Not To Use TDD?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/10/when-not-to-use-tdd/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>7 Reasons To Start Doing Test Driven Development</title>
		<link>https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/</link>
					<comments>https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 20 Sep 2021 10:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[test driven development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=656</guid>

					<description><![CDATA[<p>Why should you start doing Test Driven Development (TDD) today? What are the benefits of TDD, and how can it help the developers and business? Let&#8217;s explore 7 reasons everyone should be TDD-ing ? Moving design into code With test driven development, you create your tests before writing production code*. Having that in mind, one&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/">7 Reasons To Start Doing Test Driven Development</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Why should you start doing Test Driven Development (TDD) today? What are the benefits of TDD, and how can it help the developers and business? Let&#8217;s explore 7 reasons everyone should be TDD-ing ?</p>



<span id="more-656"></span>



<h2 class="wp-block-heading">Moving design into code</h2>



<p>With test driven development, you create your tests before writing production code*.</p>



<p>Having that in mind, one of the benefits of using TDD is that you need to <strong>move your design requirements into code before you even write a single line of business logic</strong>.</p>



<p>It means that you need to spend time thinking about <a href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/">good names</a> for your tests. I often create empty tests straightaway after staring to work on a task. Spending time to create well-named test methods can help you quickly spot missing parts in the design.</p>



<p><span style="text-decoration: underline;">*By <em>production code</em> I mean the actual business logic <em>except</em> the tests&#8217; code. This is only to differentiate here, but I personally consider my tests part of the production code in real life. Tests are as important as all the code.</span></p>



<h2 class="wp-block-heading">Finding edge cases</h2>



<p>Going further, if you create many empty tests with well-thought names, you will surely find many edge cases. Thanks to test driven development, <strong>you&#8217;ll verify the business requirements by your code <em>without </em>writing even a single line of it</strong>. Discovering edge cases and boundary conditions will let you <strong>clarify the requirements or even change/adjust them <em>before </em>any production code is written</strong> ?</p>



<h2 class="wp-block-heading">Structuring your code beforehand</h2>



<p>You&#8217;ll see that TDD forces you to think about the code you&#8217;re about to write beforehand. You&#8217;re going to think about production code to-be-written: how and where to add it, what methods, parameters and classes are needed. Thanks to that, you can quickly notice that maybe the place you&#8217;d normally place the new code in is not the best choice. Maybe it requires too much changing instead of modifying.</p>



<p>Such approach leads to <strong>taking and rethinking architectural and structural decisions before writing a single line of production code</strong>. In the end, it saves you a lot of time. Without TDD, you&#8217;d probably just add this new code where you thought it&#8217;s appropriate and struggle to refactor it later. And refactoring without tests is dangerous ?</p>



<h2 class="wp-block-heading">Allowing to refactor</h2>



<p>Test driven development is based on <a href="https://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html">red-green-refactor cycle</a>. <strong>As soon as your test is green, you can safely (for sure much more safely than without tests, especially if you combine TDD with <a href="https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/">mutation testing</a>) refactor the code you&#8217;ve just written</strong>.</p>



<p>In the end, the quality of your code is much higher than it would be without tests. You don&#8217;t feel the <em>fear of refactoring</em>, which is a common blocker for improving code quality in legacy systems.</p>



<h2 class="wp-block-heading">Making implementation very easy</h2>



<p>When you move from red to green phases of TDD, it&#8217;s time for implementation. From my experience, <strong>writing production code that satisfies TDD-produced tests is very easy</strong>. </p>



<p>I find it much easier than writing code not covered by TDD-based tests. You exactly know what to do and which tests must pass. Thanks to that, your implementation is minimal &#8211; it should only make the test(s) green.</p>



<h2 class="wp-block-heading">Creating current code documentation</h2>



<p>Implementing a new feature with test driven development will leave you with a comprehensive set of tests. From my experience, I write few times more tests with TDD than in a &#8220;traditional&#8221; <em>tests-after-code</em> mode.</p>



<p>As a nice side effect, <strong>you&#8217;re building and growing the only possible, current documentation of your code &#8211; set of your tests</strong>. Only tests can tell you the truth about your code. It can&#8217;t be achieved with any other kind of documentation. Notice one more advantage &#8211; <strong>you&#8217;re creating documentation&#8230; <em>without </em>writing any documentation!</strong> ?</p>



<p>Current, well-named tests are very helpful not only for developers, but also for the so-called <a href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/#How_naming_tests_well_can_help_the_business">business people</a>.</p>



<h2 class="wp-block-heading">Spotting architectural problems</h2>



<p>Last but not least, test driven development helps to solve application&#8217;s architectural problems. Tests should be relatively easy to write.<strong> If the test is hard to write before production code exists, it might mean that the architecture of your solution is wrong.</strong> There&#8217;s a problem somewhere that should be addressed.</p>



<p>That&#8217;s why it&#8217;s very important to start working with TDD as early as possible in your project. There might be some cases where TDD it not suitable (maybe I&#8217;ll write a separate article about it ?), but in quite mature and stable projects, it should be a gold standard. Altering the architecture is much easier early in the project. </p>



<p></p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/">7 Reasons To Start Doing Test Driven Development</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/09/7-reasons-to-start-doing-test-driven-development/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Run Cypress Tests From NUnit Test (C#)</title>
		<link>https://blog.yumasoft.pl/2021/09/run-cypress-tests-from-nunit-test-csharp/</link>
					<comments>https://blog.yumasoft.pl/2021/09/run-cypress-tests-from-nunit-test-csharp/#comments</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 13 Sep 2021 13:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[end-to-end tests]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=623</guid>

					<description><![CDATA[<p>In one of our projects, we recently started using Cypress for end-to-end testing. Cypress executes tests written in JavaScript or TypeScript. However, we wanted to first perform some data-preparation operations using C#. In fact, we needed to run Cypress tests from NUnit C# tests. In this article, I&#8217;m sharing how this can be done ?&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/run-cypress-tests-from-nunit-test-csharp/">Run Cypress Tests From NUnit Test (C#)</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In one of our projects, we recently started using <a href="https://www.cypress.io/">Cypress</a> for end-to-end testing. Cypress executes tests written in JavaScript or TypeScript. However, we wanted to first perform some data-preparation operations using C#. In fact, we needed to run Cypress tests from NUnit C# tests.</p>



<p>In this article, I&#8217;m sharing how this can be done ? It will also be useful if you use another testing framework than NUnit, but the examples are based on it.</p>



<span id="more-623"></span>



<h2 class="wp-block-heading">Starting point</h2>



<p>You can find the code accompanying this article here: <a href="https://github.com/dsibinski/cypress-csharp-example">https://github.com/dsibinski/cypress-csharp-example</a></p>



<p>Our starting point is a React application with Cypress tests:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="888" height="332" src="https://blog.yumasoft.pl/wp-content/uploads/2021/09/1_WebAppCypressTest.png" alt="React app with Cypress test" class="wp-image-628" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/09/1_WebAppCypressTest.png 888w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/1_WebAppCypressTest-300x112.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/1_WebAppCypressTest-768x287.png 768w" sizes="auto, (max-width: 888px) 100vw, 888px" /></figure></div>



<p>I assume that your tests specs are placed within <code>cypress/integration</code> folder. The only spec we have is called <code>submit_spec.ts</code> and it placed in a subfolder called <code>form</code>.</p>



<p>Now imagine, that your backend is written in C#. Maybe you&#8217;d like to perform some data initialization <em>before </em>Cypress tests are executed.</p>



<p>In our case, we have a C# backend, and we&#8217;ve already had a mechanism for running integration tests. This mechanism runs our server app with an in-memory database, which makes the maintenance of tests very easy.</p>



<p>We wanted to use the same mechanism for our new, E2E Cypress tests. It means that we would be able to write some C# initialization code (data creation mostly) and then run Cypress tests from NUnit test.</p>



<p>What we want to achieve is to have a C#-Cypress NUnit test look as follows:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="382" height="162" src="https://blog.yumasoft.pl/wp-content/uploads/2021/09/2_RunningCypressTestFromCSharpIdea.png" alt="The picture shows how to run cypress tests from nunit by only calling RunCypressTest(&quot;form/submit_spec.ts&quot;) - the method we will add soon" class="wp-image-630" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/09/2_RunningCypressTestFromCSharpIdea.png 382w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/2_RunningCypressTestFromCSharpIdea-300x127.png 300w" sizes="auto, (max-width: 382px) 100vw, 382px" /></figure></div>



<p>Let&#8217;s now see how we can implement the <code>RunCypressTest</code> method ?</p>



<h2 class="wp-block-heading">Implementing a method to run Cypress tests from NUnit</h2>



<p>To make things easier, let&#8217;s create a base class all our test classes can use. We&#8217;ll call it <code>CypressTestsBase</code> and add a <code>RunCypressTest</code> method to it: </p>



<script src="https://gist.github.com/dsibinski/70631294e17f4a0230f4fdbbfbc71fe1.js"></script>



<p>This code does the job. Few interesting parts:</p>



<ul class="wp-block-list"><li>Line 12 &#8211; I&#8217;m getting there the path to the web app workspace where <code>npx cypress run</code> command can be executed. It might be more complicated in your scenario, so you should adjust accordingly here</li><li>Lines 13-20: thanks to setting <code>RedirectStandardInput</code> to <code>true</code>, we can later execute a custom command via <code>cmd</code>; setting <code>RedirectStandardOutput</code> to <code>true</code> allows us to write everything <code>npx cypress run</code> command does to NUnit test&#8217;s output</li><li>Line 28: <code>TestContext.Out.WriteLine(cypressProcessOutput);</code> actually writes the Cypress output to NUnit test result</li><li>Line 29: here we handle errors during Cypress execution. <code>npx cypress run</code> executed via <code>cmd</code> will return a code different from 0 if anything goes wrong.</li></ul>



<p>We can now change <code>FormTests</code> class to run its corresponding Cypress test:</p>



<script src="https://gist.github.com/dsibinski/758bee0d1f3cee14375ebe65b393d5ef.js"></script>



<p>Finally, it allows to run our C# test, which then runs its corresponding Cypress spec and prints the output:</p>



<div class="wp-block-image"><figure class="aligncenter size-full is-resized"><img loading="lazy" decoding="async" src="https://blog.yumasoft.pl/wp-content/uploads/2021/09/3_CypressTestResultInNUnitResult-1.png" alt="Run Cypress tests from NUnit - sample passed test in JetBrains Rider" class="wp-image-638" width="706" height="307" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/09/3_CypressTestResultInNUnitResult-1.png 706w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/3_CypressTestResultInNUnitResult-1-300x130.png 300w" sizes="auto, (max-width: 706px) 100vw, 706px" /></figure></div>



<h2 class="wp-block-heading">Cypress errors in NUnit result</h2>



<p>Let&#8217;s see what happens if something is broken on Cypress/web app&#8217;s side. Let&#8217;s run our test, but with our web app not running.</p>



<p>The NUnit test fails, and we can clearly see what was wrong:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="999" height="323" src="https://blog.yumasoft.pl/wp-content/uploads/2021/09/4_CypressTestFailedNUnitResult.png" alt="Run Cypress tests from NUnit - failed test in JetBrains Rider, all details from cypress visible" class="wp-image-640" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/09/4_CypressTestFailedNUnitResult.png 999w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/4_CypressTestFailedNUnitResult-300x97.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/09/4_CypressTestFailedNUnitResult-768x248.png 768w" sizes="auto, (max-width: 999px) 100vw, 999px" /></figure></div>



<p>You will see similar errors if something goes wrong in a Cypress test. Cypress also <a href="https://docs.cypress.io/guides/guides/screenshots-and-videos">saves compressed videos and screenshots</a>, so if something goes wrong, diagnosing such failed tests is very easy.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>I hope you found this article on how to run Cypress tests from NUnit useful. Remember that it not only works with NUnit &#8211; it will be suitable for any testing framework. You might need to adjust some parts of the solution, e.g. printing the results to the test result&#8217;s output.</p>



<p>This solution allowed us to improve our testing by adding a new type of tests to our <a href="https://blog.yumasoft.pl/2021/07/how-to-configure-jest-tests-on-teamcity/">pipeline</a>. Right next to <a href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/">proper naming</a> and <a href="https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/">mutation testing</a>, E2E tests add another layer of security and improve the quality of our software.</p>



<p>Once more, you can find the complete source code <a href="https://github.com/dsibinski/cypress-csharp-example">here</a>. If you want, feel free to copy it and change it according to your needs ?</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/run-cypress-tests-from-nunit-test-csharp/">Run Cypress Tests From NUnit Test (C#)</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/09/run-cypress-tests-from-nunit-test-csharp/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
			</item>
		<item>
		<title>Foreach, IEnumerable and IEnumerator in C#</title>
		<link>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/</link>
					<comments>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 06 Sep 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.net framework]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dotnet]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=593</guid>

					<description><![CDATA[<p>Today, we&#8217;re taking a deeper look at foreach loop in C#. What does a collection need to be able to use it in a foreach loop? Does it have to implement IEnumerable interface? These questions are often asked during interviews, so it&#8217;s worth knowing the answers ? We will go through a step-by-step example in&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/">Foreach, IEnumerable and IEnumerator in C#</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Today, we&#8217;re taking a deeper look at <code>foreach</code> loop in C#. What does a collection need to be able to use it in a <code>foreach</code> loop? Does it have to implement <code>IEnumerable</code> interface? These questions are often asked during interviews, so it&#8217;s worth knowing the answers ?</p>



<p>We will go through a step-by-step example in building our own custom collection to see how all that works. Let&#8217;s dive in! ?</p>



<span id="more-593"></span>



<p><em>Throughout this article, I&#8217;m working with a Unit Tests project using .NET 5, C# 9.0 and <a href="https://nunit.org/">NUnit</a>. It makes it easier to play with the code on your own. We can create our custom collection and at the same time try it out in a <code>foreach</code> loop in a test method. I recommend this approach for testing out various programming concepts for yourself ?</em></p>



<h2 class="wp-block-heading">Custom collection implementing IEnumerable&lt;T&gt;</h2>



<p>First, we want to implement our own, custom collection in C#. The most obvious solution is to implement <code>IEnumerable&lt;T></code> interface. Our IDE will require our class to implement <code>IEnumerator GetEnumerator()</code> and <code>IEnumerator IEnumerable.GetEnumerator()</code> methods, so let&#8217;s do that:</p>



<script src="https://gist.github.com/dsibinski/f40065534bf002dbdce0e834db636d3c.js"></script>



<p>Of course, this is just an example to satisfy the <code>foreach</code> loop, so we won&#8217;t care about the actual implementation of these methods ?</p>



<p>Custom collection implemented in such a way can be used in <code>foreach</code> loop: </p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-599" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_ForeachIEnumerableCollection-1-300x180.png 300w" sizes="auto, (max-width: 444px) 100vw, 444px" /></figure></div>



<h2 class="wp-block-heading">Does foreach require IEnumerable?</h2>



<p>Let&#8217;s try to get rid of implementing <code>IEnumerable</code> interface. As soon as we do it, our IDE complains:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="856" height="394" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable.png" alt="Custom collection not implement IEnumerable and IDE complaining about &quot;IEnumerable.GetEnumerator&quot; method" class="wp-image-600" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable.png 856w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable-300x138.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_IDEErrorIEnumerable-768x353.png 768w" sizes="auto, (max-width: 856px) 100vw, 856px" /></figure></div>



<p>Let&#8217;s try to remove <code>IEnumerable.GetEnumerator()</code> method completely, so our custom collection looks as follows:</p>



<script src="https://gist.github.com/dsibinski/af9b9f9b308e471652f2dcd754754bc6.js"></script>



<p>Now guess what &#8211; we can still use <code>MyCollection</code> within the <code>foreach</code> loop!</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-601" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_Foreach_Collection_with_GetEnumerator_method-300x180.png 300w" sizes="auto, (max-width: 444px) 100vw, 444px" /></figure></div>



<p>So you already know that, when asked during an interview whether <code>foreach</code> needs a collection to implement <code>IEnumerable</code>, the answer is no ?</p>



<h2 class="wp-block-heading">Custom IEnumerator</h2>



<p>Currently, our collection has a single <code>GetEnumerator()</code> method returning <code>IEnumerator&lt;MyObject></code>. We already know that this method is needed in a collection to be able to use it within a <code>foreach</code> loop. </p>



<p>However, let&#8217;s work on what this method returns. We&#8217;ll implement our custom <code>IEnumerator</code>. Again &#8211; the most obvious solution is to create a class implementing <code>IEnumerator&lt;T></code> interface:</p>



<script src="https://gist.github.com/dsibinski/014116fc47bf9159dcfe3e44bb54b6fe.js"></script>



<p>That&#8217;s the implementation proposed by the IDE (Rider). We can now change our collection to use this custom enumerator. See that it can still be used within <code>foreach</code>:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="467" height="466" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator.png" alt="Custom collection (without implementing any interface) returns a custom enumerator MyObjectEnumerator" class="wp-image-603" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator.png 467w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator-300x300.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/4_Custom_Collection_With_Custom_Enumerator-150x150.png 150w" sizes="auto, (max-width: 467px) 100vw, 467px" /></figure></div>



<p>So far, so good. But why all these methods in <code>MyObjectEnumerator</code>? ?</p>



<h2 class="wp-block-heading">Does foreach need an enumerator implementing IEnumerator?</h2>



<p>If we remove inheritance from <code>IEnumerator</code> from <code>MyObjectEnumerator</code>, the IDE only complains about <code>IEnumerator.Current</code> property, so let&#8217;s get rid of it. Our custom enumerator now looks as follows:</p>



<script src="https://gist.github.com/dsibinski/bb9e8ef54834656d4994e337c00f6c8a.js"></script>



<p>Yeah, you guessed it again &#8211; we can still use our collection in a <code>foreach</code> loop ?</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="444" height="266" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface.png" alt="Custom collection used in a foreach loop (C#)" class="wp-image-604" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface.png 444w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/5_Foreach_custom_enumerator_no_interface-300x180.png 300w" sizes="auto, (max-width: 444px) 100vw, 444px" /></figure></div>



<p>However&#8230; Does our custom enumerator really needs all of these stuff:  <code>MoveNext(), Reset()</code>, <code>Dispose()</code> and <code>MyObject Current</code> ? Let&#8217;s remove all of them and see what our IDE tells us:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="1024" height="517" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-1024x517.png" alt="IDE (JetBrains Rider) error:
Type 'ForeachFun.MyCollection' cannot be used in 'foreach' statement because it neither implements 'IEnumerable' or 'IEnumerable', nor has suitable 'GetEnumerator' method which return type has 'Current' property and 'MoveNext' method" class="wp-image-605" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-1024x517.png 1024w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-300x151.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error-768x388.png 768w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/6_Foreach_empty_Enumerator_error.png 1153w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></figure></div>



<p>That&#8217;s the error from IDE when trying to iterate through our custom collection in <code>foreach</code>:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p></p><cite>Type &#8216;ForeachFun.MyCollection&#8217; cannot be used in &#8216;foreach&#8217; statement because it neither implements &#8216;IEnumerable&#8217; or &#8216;IEnumerable&#8217;, <strong>nor has suitable &#8216;GetEnumerator&#8217; method which return type has &#8216;Current&#8217; property and &#8216;MoveNext&#8217; method</strong></cite></blockquote>



<p>This error actually tells us everything. This is the ultimate answer to the legendary C# interview question: &#8220;What does a collection need to be able to use it in <code>foreach</code> loop?&#8221;. In other words: &#8220;Is it necessary for a collection to implement <code>IEnumerable</code> to use it in a <code>foreach</code> loop?&#8221;</p>



<p>The answer is:<strong> a collection needs to have a <code>GetEnumerator</code>() method returning an object of type having <code>Current</code> property and <code>bool MoveNext()</code> method. No interfaces are required anywhere here ?</strong></p>



<p>The compiler uses duck typing to find these two necessary ingredients of the type returned from <code>GetEnumerator()</code>. It means that is looks for these properties by text. Later, depending on the type of <code>Current</code> property, a single element inside the <code>foreach</code> is typed accordingly. Only if this duck searching fails, the compiler checks whether the collection implements the interfaces.</p>



<p>In the end, this is our simplest and fully legit code (except the actual implementations of the methods, which is out of scope of this article):</p>



<script src="https://gist.github.com/dsibinski/99a2559ef72c2f493a231dc13879b4ec.js"></script>



<h2 class="wp-block-heading">Summary</h2>



<p>I hope you got to know something new about <code>foreach</code> loop from this article. This may not sound like a knowledge you&#8217;d need on a daily basis, but it&#8217;s worth knowing how stuff works under the hood ? Plus, you can always score a point during your next interview ?!</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/">Foreach, IEnumerable and IEnumerator in C#</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/09/foreach-ienumerable-and-ienumerator-in-c/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Make Your Tests Bulletproof With Mutation Testing</title>
		<link>https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/</link>
					<comments>https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 23 Aug 2021 01:42:02 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[mutation testing]]></category>
		<category><![CDATA[mutation tests]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=557</guid>

					<description><![CDATA[<p>What is mutation testing? How can we generate test cases &#8220;for free&#8221;? How to make our software tests bulletproof, so we can refactor the code with more confidence? At Yumasoft, we believe that testing is an inseparable part of software development. Mutation testing, which recently got a bit more attention in programming communities, is a&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/">Make Your Tests Bulletproof With Mutation Testing</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>What is mutation testing? How can we generate test cases &#8220;for free&#8221;? How to make our software tests bulletproof, so we can refactor the code with more confidence?</p>



<p>At Yumasoft, we believe that <a href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/">testing</a> is an inseparable part of software development. Mutation testing, which recently got a bit more attention in programming communities, is a great way of improving our tests. In today&#8217;s article, we&#8217;re exploring what mutation testing is and why everyone should be using it ?</p>



<span id="more-557"></span>



<h2 class="wp-block-heading">What is mutation testing?</h2>



<p>To make it clear, mutation testing isn&#8217;t just a new type of tests you can write. At least not in a casual sense of a test ?</p>



<p><strong>Mutation testing is a technique for validating</strong> <strong>your already-existing tests</strong>. They basically allow <strong>to test our tests</strong>.</p>



<p>Mutation tests are not for people who don&#8217;t write tests (go away, we don&#8217;t like you!). They are for people who care about testing and want to make their tests better.</p>



<h2 class="wp-block-heading">How does mutation testing work?</h2>



<p>Mutation tests introduce <em>mutations </em>into our source code under tests (you can call it production code). Mutations can be any changes in the source code you can think of. Let it be a modification of a condition within an <code>if</code> statement, replacement of a <code>string</code> value or change of an arithmetic operator &#8211; you name it. All you need to know is that <strong>mutation testing is based on automatically introducing changes to your source code</strong>.</p>



<p>Our codebase with such a change (a single one) introduced is called a <em>mutant</em>. It makes sense &#8211; our production code is now somehow <em>mutated</em>.</p>



<p>What happens with such a mutant then? All our existing tests are executed against it. Such tests&#8217; execution may produce two outcomes:</p>



<ul class="wp-block-list"><li>all tests have passed &#8211; that&#8217;s a <strong>bad scenario</strong>. It means that our <strong>mutant has <em>survived</em>.</strong> In other words, it means that a modification of our production source code wasn&#8217;t detected by our tests suite</li><li>at least one test has failed &#8211; that&#8217;s a <strong>good scenario</strong>. It means that our <strong>mutant has been <em>killed</em></strong>. This is what we want, because it means our tests are well-covering and detect changes in the production code.</li></ul>



<p>You can see the flow of mutation testing on the following schema:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="353" height="580" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_MutationTestsSchema.png" alt="Mutation testing schema" class="wp-image-562" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_MutationTestsSchema.png 353w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_MutationTestsSchema-183x300.png 183w" sizes="auto, (max-width: 353px) 100vw, 353px" /><figcaption>Source: <a href="https://peterevans.dev/posts/mutation-testing/">The blog of Peter Evans</a></figcaption></figure></div>



<h2 class="wp-block-heading">Example of mutation tests</h2>



<p>To make mutation tests more practical, let&#8217;s see an example. We&#8217;ll be using <a href="https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/">StrykerJS </a>for production code written in TypeScript.</p>



<p>This is our production code:</p>



<script src="https://gist.github.com/dsibinski/38b88a48d8a5a715a3745bc4e6954c3c.js"></script>



<p>We have of course written some tests for this code. When we execute these tests with <a href="https://blog.yumasoft.pl/2021/07/how-to-configure-jest-tests-on-teamcity/">jest</a>, we can see the following result:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="956" height="598" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_TestsFullCoverageExample.png" alt="Output of jest tests" class="wp-image-566" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_TestsFullCoverageExample.png 956w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_TestsFullCoverageExample-300x188.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_TestsFullCoverageExample-768x480.png 768w" sizes="auto, (max-width: 956px) 100vw, 956px" /></figure></div>



<p>So we have 100% coverage for <code>DiscountApplier</code> class! What&#8217;s more, we have 100% statements, branch, functions and line coverage! This sounds perfect, right? Why should we bother more? ?</p>



<p>Let&#8217;s deep dive and run StrykerJS mutator against our app. After <a href="https://stryker-mutator.io/docs/stryker-js/getting-started/">installing</a> and <a href="https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/">configuring Stryker</a> properly, we can execute <code>npx stryker run</code> command. That&#8217;s the final result:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="650" height="101" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_StrykerRunResult.png" alt="Output of npx stryker run command. 46 mutants killed, 10 survived, 82.14% mutant coverage" class="wp-image-567" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_StrykerRunResult.png 650w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_StrykerRunResult-300x47.png 300w" sizes="auto, (max-width: 650px) 100vw, 650px" /></figure></div>



<p>Whoooaa&#8230; we see here some 82.14% value, not 100% anymore ? This is what I call <strong>mutant coverage</strong>.</p>



<p>Remember what we said above about survived and killed mutants? Pay attention to our mutations results above &#8211; we have <strong>46 mutants killed</strong>, but <strong>10 of them survived</strong>. It means that we have a potential to add more tests to cover these scenarios.</p>



<p>We will not be going through each mutant and adding the test for it in this article, but I can tell you what these results can give you. In the beginning, <strong>when our mutant coverage was 82.14% with 10 mutants survived, we had 6 unit tests</strong> written for <code>DiscountApplier</code> class. In the end, after working out and killing each mutant one-by-one, <strong>we finished with 12 unit tests and 100% mutant</strong> coverage.</p>



<p><strong>In 10 minutes</strong> <strong>(time needed to add these 6 tests), I got</strong> <strong>twice as many unit tests as in the beginning</strong>. Now, both &#8220;traditional&#8221; and mutant coverages are 100%. My confidence in refactoring or modifying the production code is much higher now. Notice that we got this all &#8220;for free&#8221;. Mutation testing tool (StrykerJS in that case) did everything for us. This is huge! ?</p>



<h2 class="wp-block-heading">How to start writing mutation tests</h2>



<p>Just find a proper mutation testing tool for the framework/programming language you work with. Here are a few most popular examples:</p>



<ul class="wp-block-list"><li>JavaScript/TypeScript/C#/Scala: <a href="https://stryker-mutator.io/">Stryker mutator</a></li><li>Ruby: <a href="https://github.com/mbj/mutant">mutant</a></li><li>Java: <a href="https://pitest.org/">Pitest</a></li><li>PHP: <a href="https://infection.github.io/">Infection</a></li></ul>



<p>Go straight to the docs of your tool of choice and start mutating ? The messages about each mutant are very clear, so adding new tests to kill them will be very easy. It&#8217;s like someone sitting next to you and telling you exactly what test you should add for your code. That&#8217;s actually a pretty decent solution for anyone who doesn&#8217;t like writing tests ? </p>



<p>I don&#8217;t see any reason why anyone would not use mutation testing. It&#8217;s such a great tooling that I don&#8217;t see any disadvantages in using it. It can greatly help you with TDD as well as an additional &#8220;layer&#8221; of inventing new test cases and patching your code. Believe me, you&#8217;ll see the benefits straightaway.</p>



<p>So &#8211; download one of the mutation tools and make your tests bulletproof today ? Or at least see how bad they are now ?</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/">Make Your Tests Bulletproof With Mutation Testing</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/08/make-your-tests-bulletproof-with-mutation-testing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How To Fix JSON.NET Circular References ($ref) In JavaScript</title>
		<link>https://blog.yumasoft.pl/2021/08/how-to-fix-json-net-circular-references-ref-in-javascript/</link>
					<comments>https://blog.yumasoft.pl/2021/08/how-to-fix-json-net-circular-references-ref-in-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Sun, 15 Aug 2021 07:30:27 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[json.net]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=518</guid>

					<description><![CDATA[<p>If you work with a .NET backend that uses JSON.NET for serialization, you might encounter such weird things in the JSON result returned from a controller: But what you actually want is the real object present there: After reading this article, you will know how to achieve that ? JSON.NET circular references are the issue&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/08/how-to-fix-json-net-circular-references-ref-in-javascript/">How To Fix JSON.NET Circular References ($ref) In JavaScript</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you work with a .NET backend that uses <a href="https://www.newtonsoft.com/json">JSON.NET</a> for serialization, you might encounter such weird things in the JSON result returned from a controller:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="373" height="311" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png" alt="JSON result from ASP.NET controller with $ref: &quot;1&quot; instead of a real object. Example of JSON.NET circular references" class="wp-image-519" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png 373w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample-300x250.png 300w" sizes="auto, (max-width: 373px) 100vw, 373px" /></figure></div>



<p>But what you actually want is the real object present there:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="560" height="323" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved-1.png" alt="JSON result from ASP.NET controller with $ref: &quot;1&quot; replaced with a real object's content" class="wp-image-535" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved-1.png 560w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved-1-300x173.png 300w" sizes="auto, (max-width: 560px) 100vw, 560px" /></figure></div>



<p>After reading this article, you will know how to achieve that ?</p>



<span id="more-518"></span>



<h2 class="wp-block-heading">JSON.NET circular references are the issue</h2>



<p>Let&#8217;s take a look at our problematic JSON response object once again:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="373" height="311" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png" alt="JSON result from ASP.NET controller with $ref: &quot;1&quot; instead of a real object" class="wp-image-519" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png 373w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample-300x250.png 300w" sizes="auto, (max-width: 373px) 100vw, 373px" /></figure></div>



<p><code>$ref: "1"</code> is basically a reference to another object, which has already been serialized. In that case, the <code>BestFriend</code> field references the first element of the result array with <code>$id: "1"</code>. It turns out that these are <strong>JSON.NET circular references</strong>. However, you don&#8217;t want these references in your client-side JS code &#8211; you need the actual objects to work with.</p>



<p>I struggled with this issue some time ago in my JavaScript code. In the beginning, I had no idea it might come from the fact that JSON.NET is used for serialization (thanks to our colleague Rafał for pointing that out to me ?). Let&#8217;s see what exactly happens here and why.</p>



<h2 class="wp-block-heading">JSON.NET serialization</h2>



<p>The JS example presented above shows a JSON result received from the following ASP.NET controller method:</p>



<script src="https://gist.github.com/dsibinski/9c1decb2cf139f8078d31d470f643f21.js"></script>



<p>This is the full content of <code>json</code> string after serialization:</p>



<script src="https://gist.github.com/dsibinski/72a6e910965e7f0081ffbf6a0671ef2e.js"></script>



<p>Of course, this is great that JSON.NET does that. Why would we repeat the same objects multiple times in JSONs? The optimization here is that the same objects are serialized once and referenced from all places that use them.</p>



<p>However, if such JSONs are sent to the browser, fields with refs are of no use. We need the actual objects to be there, so we can process the results correctly using JavaScript.</p>



<h2 class="wp-block-heading">Solution 1: fix the issue by reconfiguring JSON.NET serializer</h2>



<p>The first obvious solution could be to configure JSON.NET to not use its optimization for references. Quickly searching through its documentation, we find that <a href="https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_PreserveReferencesHandling.htm">PreserveReferencesHandling</a> setting is responsible for that.</p>



<p>If we change our controller&#8217;s code and serialize objects with <code>PreserveReferencesHandling</code> set to <code>None</code>:</p>



<script src="https://gist.github.com/dsibinski/bd56f8b632852ec03daa6a95fdefe658.js"></script>



<p>Our JSON file will look exactly as we&#8217;d expect:</p>



<script src="https://gist.github.com/dsibinski/2386331dd58e4339c7aaace0bf6a9cd0.js"></script>



<p>However, why would we disable JSON.NET circular references? This optimization can sometimes save us huge amounts of data to be sent over the wire. If you have thousands of objects, it might not make sense in sending them all to the client-side code.</p>



<p>You may also have no control of the backend/API you receive the data from. It might as well be dangerous to change the JSON serialization settings, especially if you work on a big project.</p>



<p>If reconfiguration of JSON.NET circular references serialization is not possible in your case, see the other solution (which we also use).</p>



<h2 class="wp-block-heading">Solution 2: resolve circular references using JavaScript</h2>



<p>So we are back to this state in JavaScript:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="373" height="311" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png" alt="JSON result from ASP.NET controller with $ref: &quot;1&quot; instead of a real object" class="wp-image-519" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample.png 373w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/1_CircularReferenceExample-300x250.png 300w" sizes="auto, (max-width: 373px) 100vw, 373px" /></figure></div>



<p>What we want is to have the full objects&#8217; contents instead of <code>$ref</code> elements in our JSON result.</p>



<p>In fact, all the data we need is already there. The first element of the array with <code>$id: "1"</code> is object that should be put in place of all <code>$ref: "1"</code> references.</p>



<p>As you can imagine, this requires a mechanism that would traverse the results tree and replace all these values according to IDs of the referenced objects.</p>



<p>Fortunately, we don&#8217;t need to implement it ourselves. There are few implementations of such a tool, circulating the web.</p>



<p>We use something called <code>JsonNetDecycle</code> which we found few years back already. I noticed there&#8217;s a new version of it ported to TypeScript: <a href="https://github.com/jmackay/angular2-demoproject-aspnetcore/blob/master/Source/Angular2Demo.Web/wwwroot/lib/jsonNetDecycle.ts">jsonNetDecycle.ts</a>. It doesn&#8217;t provide full type support as it is a few years old already, and I didn&#8217;t try it. But you can if you use <a href="https://blog.yumasoft.pl/2021/06/migrating-javascript-react-app-to-typescript/">TypeScript</a> ? There&#8217;s also a <code>cycle.js</code> solution available <a href="https://github.com/douglascrockford/JSON-js/blob/master/cycle.js">here</a> and recommended by many folks. I believe it may also solve our issue, but again &#8211; this is not what we are using.</p>



<p>The version of the  <code>JsonNetDecycle</code>  we use is <a href="https://gist.github.com/johnbabb/2d69374455e386eae87a">this one</a>. Simply create a new file called <code>JsonNetDecycle.js</code> in your project and copy this Gist&#8217;s contents to this file. You can skip the last part starting with <code>(function(console)</code> (line 112) &#8211; we won&#8217;t need it.</p>



<p>Now, we can use the exported <code>JsonNetDecycle.retrocycle()</code> function to &#8220;fix&#8221; our JSON:</p>



<script src="https://gist.github.com/dsibinski/800bd926a0e44d206df688edf4c86bec.js"></script>



<p>Let&#8217;s see whether this works.</p>



<p>This is what we get from the API before resolving JSON.NET circular references:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="593" height="311" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_CircularReferencesExampleWithDetails.png" alt="JSON result from ASP.NET controller with $ref: &quot;1&quot; instead of a real object" class="wp-image-532" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_CircularReferencesExampleWithDetails.png 593w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/2_CircularReferencesExampleWithDetails-300x157.png 300w" sizes="auto, (max-width: 593px) 100vw, 593px" /></figure></div>



<p>So we still have references there instead of real objects.</p>



<p>Now let&#8217;s see what happens with the <code>result</code> object after executing <code>JsonNetDecycle.retrocycle()</code> on it:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="560" height="323" src="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved.png" alt="JSON result from ASP.NET controller using JSON.NET without JSON.NET circular references" class="wp-image-533" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved.png 560w, https://blog.yumasoft.pl/wp-content/uploads/2021/08/3_CurcularReferencesRemoved-300x173.png 300w" sizes="auto, (max-width: 560px) 100vw, 560px" /></figure></div>



<p>Wohhooa! That&#8217;s what we wanted ? There are no circular references in our JSON response anymore!</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/08/how-to-fix-json-net-circular-references-ref-in-javascript/">How To Fix JSON.NET Circular References ($ref) In JavaScript</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/08/how-to-fix-json-net-circular-references-ref-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Why Naming Tests Matters?</title>
		<link>https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/</link>
					<comments>https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Mon, 26 Jul 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[integration tests]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[unit tests]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=418</guid>

					<description><![CDATA[<p>Do you even care about naming tests? Or maybe you use some random, not-much-telling names for your test methods? At Yumasoft, we treat testing as an inseparable part of software development. It turns out that the tests you write can tell a lot about your software. However, when named carelessly, these tests have much less&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/">Why Naming Tests Matters?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Do you even care about naming tests? Or maybe you use some random, not-much-telling names for your test methods? At Yumasoft, we treat testing as an inseparable part of software development. It turns out that the tests you write can tell a lot about your software. However, when named carelessly, these tests have much less value. Let&#8217;s talk about naming tests properly, so both programmers and business can get more value of them.</p>



<span id="more-418"></span>



<h2 class="wp-block-heading">Consequences of bad tests&#8217; names</h2>



<p>You may think I&#8217;m exaggerating here. Why would I care about naming my tests methods? These are only tests&#8230; Let&#8217;s not waste time on thinking about such unimportant things. However, before we dig more into that, let&#8217;s see how typical badly-named tests look like. Below, I&#8217;m presenting the types of badly named tests that I see most often. I also used to name my tests like that ?</p>



<h3 class="wp-block-heading">Random names</h3>



<p>This is what I like the most:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="346" height="134" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/1_RandomTestsNames.png" alt="Rider and unit tests result: Test1, Something1, Test11..." class="wp-image-426" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/1_RandomTestsNames.png 346w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/1_RandomTestsNames-300x116.png 300w" sizes="auto, (max-width: 346px) 100vw, 346px" /></figure></div>



<p>Just random names. Surprisingly, I see that quite often. What does such a list of passing tests tell us? Why do they pass? What do these tests verify? We know nothing about them. We can only see that <em>there are some test</em>s. What they test, how and under what conditions &#8211; can&#8217;t say ?&#x200d;<img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2642.png" alt="♂" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>



<h3 class="wp-block-heading">Tested object described</h3>



<p>This is another type of tests I sometimes encounter. A bit better, yet still far from fully informative:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="346" height="152" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/2_ObjectsUnderTestsNamed.png" alt="Naming tests with objects under tests named, for example GetUser_Test1, Login_Test1. Class named UsersServiceTests" class="wp-image-428" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/2_ObjectsUnderTestsNamed.png 346w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/2_ObjectsUnderTestsNamed-300x132.png 300w" sizes="auto, (max-width: 346px) 100vw, 346px" /></figure></div>



<p>Looking at these tests list, we can at least say a few things:</p>



<ul class="wp-block-list"><li>there exists a <code>UsersService</code> class which is under tests here</li><li><code>UsersService</code> has at least two methods: <code>GetUser</code> and <code>Login</code></li><li>under some <em>unknown conditions</em>, <code>GetUser</code> and <code>Login</code> methods <em>probably</em> work</li></ul>



<p>However, we still don&#8217;t know what it <em>actually means</em> that these tests pass. Does it mean that login and getting users are well-tested and work correctly? What conditions need to be met so the user can log in? What parameters do we have to provide to <code>GetUser</code> method to use it properly? Again &#8211; we can&#8217;t say.</p>



<h3 class="wp-block-heading">Expected outcome described</h3>



<p>Let&#8217;s go one step further. A bit improved tests might look as follows:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="384" height="157" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1.png" alt="Naming tests with objects under test and expected outcomes named, for example: GetUser_ReturnsUserData " class="wp-image-432" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1.png 384w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1-300x123.png 300w" sizes="auto, (max-width: 384px) 100vw, 384px" /></figure></div>



<p>Someone tried to be a bit more descriptive here. That&#8217;s good, isn&#8217;t it? ? Let&#8217;s try to see how many things we can say about our codebase now:</p>



<ul class="wp-block-list"><li>there exists a <code>UsersService</code> class which is under tests here</li><li><code>UsersService</code> has at least two methods: <code>GetUser</code> and <code>Login</code></li><li><code>GetUser</code> method returns user data</li><li><code>GetUser</code> might <em>sometimes</em> throw <code>UserNotFoundException</code></li><li><code>Login</code> logs in the user correctly under <em>some</em> conditions</li><li><code>Login</code> returns a user token</li><li><code>Login</code> might <em>sometimes</em> throw <code>WrongCredentialsException</code></li></ul>



<p>We already know much more about our codebase! However, notice that we still often use very uncertain words like &#8220;sometimes&#8221; or &#8220;some&#8221;. It doesn&#8217;t feel we&#8217;re sure about these outcomes. We still don&#8217;t know <em>under what conditions</em> these tests pass or exceptions are thrown.</p>



<h2 class="wp-block-heading">Why badly named tests are bad?</h2>



<p>I think you already know that at this point. Badly named tests are confusing. They don&#8217;t tell us enough about our codebase. One of the goals of tests is to be a <em>live code documentation.</em> But how can they be if they are very undescriptive? How can we know what happens in case such a test fails: </p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="617" height="152" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/4_UndescriptiveTestFails.png" alt="Naming tests and failure of nondescriptive test" class="wp-image-434" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/4_UndescriptiveTestFails.png 617w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/4_UndescriptiveTestFails-300x74.png 300w" sizes="auto, (max-width: 617px) 100vw, 617px" /></figure></div>



<p>What do we know looking at that? Why could this test fail? If there&#8217;s a non-technical person looking as this result in a CI system while programmers are not around &#8211; how can (s)he tell what&#8217;s wrong and how to potentially fix that?</p>



<p>This result tells us nothing more than the <code>Login</code> process does not throw <code>WrongCredentialsException</code>. But we don&#8217;t know <em>when </em>it should throw this error. What are the <em>conditions</em> that should be met for this exception to be thrown? Again &#8211; we can&#8217;t say.</p>



<p>Notice that I used the best from all examples we had so far. What if this test was named <code>Test1()</code> and it failed? Does it mean anything? Is it something serious blocking the release of our app, or we can ignore it? ?</p>



<p>I guess you now see very well what I mean by badly named tests. I hope you also understand &#8211; and agree ? &#8211; that  such tests&#8217; names are bad.</p>



<p>Fortunately, we all here write tests, right? ? So, if we are already putting some effort in creating tests, let&#8217;s put a bit more to make them informative and useful for others.</p>



<h2 class="wp-block-heading">Naming tests done well</h2>



<p>There are a lot of unit tests naming conventions. You can read about them in many great articles like <a href="https://medium.com/@stefanovskyi/unit-test-naming-conventions-dd9208eadbea">this one</a>. There&#8217;s a lot of <a href="https://stackoverflow.com/questions/155436/unit-test-naming-best-practices">discussion</a> around naming tests conventions.</p>



<p>However, independently of which naming strategy you choose, I think a well named test should tell someone who reads its name the following things:</p>



<ul class="wp-block-list"><li><strong>what</strong> is tested (class name)</li><li><strong>which part</strong> of it is tested (method name)</li><li>what is the <strong>expected result</strong></li><li>what are the <strong>conditions</strong> for the expected result</li></ul>



<p>Many of tests naming conventions fulfil these 4 requirements.</p>



<p>Let&#8217;s come back to our last example of badly named tests (but still its best version): </p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="384" height="157" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1.png" alt="Tests named with objects under test and expected outcomes named, for example: GetUser_ReturnsUserData " class="wp-image-432" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1.png 384w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/3_ObjectsAndOutcomesNamed-1-300x123.png 300w" sizes="auto, (max-width: 384px) 100vw, 384px" /></figure></div>



<p>Let&#8217;s use one of the naming conventions I like:</p>



<p><em>MethodName</em>_<strong>Should</strong>_<em>ExpectedResult</em>_<strong>When</strong>_<em>Conditions</em></p>



<p>Applying this to our tests, the final result is as follows:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="677" height="158" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/5_WellNamedTests-1.png" alt="Well named tests, for example GetUser_Should_ReturnUserData_When_ExistingUserIdProvided" class="wp-image-437" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/5_WellNamedTests-1.png 677w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/5_WellNamedTests-1-300x70.png 300w" sizes="auto, (max-width: 677px) 100vw, 677px" /></figure></div>



<p>Now, for each test, we can see what is tested (<code>UsersService</code>), which part of it (e.g. <code>Login</code> method), what&#8217;s the expected result (e.g. <code>ReturnUserToken</code>) and under what conditions (e.g. <code>CorrectUsernameAndPasswordProvided</code>). This is very descriptive and valuable. Now, when something goes wrong:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="891" height="147" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/6_WellNamedTestsOneFailing.png" alt="One test failing from all properly named. Thanks to its descriptiveness, it's easy to see what's wrong" class="wp-image-438" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/6_WellNamedTestsOneFailing.png 891w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/6_WellNamedTestsOneFailing-300x49.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/6_WellNamedTestsOneFailing-768x127.png 768w" sizes="auto, (max-width: 891px) 100vw, 891px" /></figure></div>



<p>We know a lot more than before. We can easily see that when wrong credentials are provided, the <code>WrongCredentialsException</code> is not thrown (while it should). It makes it easier to judge whether this is blocking for the release of our app or not. We probably don&#8217;t want to let users login with incorrect credentials ?</p>



<p>Another, very important factor for naming your tests well is that <strong>the whole team agrees on one naming convention</strong>. I think it&#8217;s even more important than choosing a particular naming convention. Choose whatever suits you and your team. There are <a href="https://medium.com/@stefanovskyi/unit-test-naming-conventions-dd9208eadbea">a lot of options</a>, but in the end it doesn&#8217;t really matter which one you agree on. Just stick to it and make sure it delivers all value you need.</p>



<h2 class="wp-block-heading">How naming tests well can help the programmers </h2>



<p>Correctly and descriptively named tests can help you as a programmer. Imagine that you are about to introduce a change in <code>UsersService</code>, but you have no idea how it works. The first thing I do in such cases is to open a corresponding tests file and scan all unit tests.</p>



<p>First, I expect that the tests file is named <code>UsersServiceTests</code>, because my team follows a common naming convention. Thanks to that, I can immediately open this class in my IDE and quickly scan all unit tests names:</p>



<div class="wp-block-image"><figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="884" height="211" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/7_QuickTestsScan.png" alt="Quickly scanning well-named tests in a test class as in IDE" class="wp-image-442" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/7_QuickTestsScan.png 884w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/7_QuickTestsScan-300x72.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/7_QuickTestsScan-768x183.png 768w" sizes="auto, (max-width: 884px) 100vw, 884px" /></figure></div>



<p>This tells me a lot about the <code>UsersService</code>. If I want to see only how <code>Login</code> method works, I can easily filter out all tests with names starting with &#8220;Login&#8221;. Again &#8211; thanks to following the naming convention.</p>



<p>The next thing is that when you start making changes to the production code of <code>UsersService</code> and one of the tests fails, you know what&#8217;s wrong very quickly.</p>



<p>Another advantage of naming tests properly is when you are adding new tests. If you&#8217;re obliged to follow a descriptive tests naming convention, you need to think very well what your new code under tests should do and under what conditions. This makes your production code more structured and well-thought. Just give it a try, especially if you use TDD. I often start my TDD session with writing empty tests named correctly. This gives me many ideas of the production code I&#8217;m going to write straight after.</p>



<h2 class="wp-block-heading">How naming tests well can help the business</h2>



<p>I think I don&#8217;t need to explain that to you anymore. However, remember that your tests might be useful for other people than programmers. All non-technical people involved in the project can have a great use of the tests if you name them correctly.</p>



<p>I hope that your <a href="https://blog.yumasoft.pl/2021/07/how-to-configure-jest-tests-on-teamcity/">tests are executed as part of a CI process</a> you use for your app deployment. As I wrote before, imagine having a late Friday release of your app. As a programmer, you&#8217;re the last one to commit this one last bug fix, and you go home. The project manager stays alone, waiting for the CI build to finish, so he can accept and deploy the new version of the app. But then, one of the tests fails. If your tests are named well, he will be able to easily judge whether this is blocking the deployment or not. I think that gives a lot of value to the business.</p>



<p>In case of some applications, where classes/services are created close to the domain of the app, business people can also explore the set of tests for a given service to grasp an idea of how it works and why it works as it does. Similarly, when you explore the tests class in your IDE. This wouldn&#8217;t be possible in every project, but it might also become a benefit of well-named tests in some cases.</p>



<h2 class="wp-block-heading">Summary</h2>



<p>I hope that after reading this article, you know why naming tests matters. Giving your test a descriptive name is a small effort, but it brings huge benefits. Both to your fellow programmers, but also to non-technical, so-called &#8220;business people&#8221;.</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/">Why Naming Tests Matters?</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/07/why-naming-tests-matters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How To Use StrykerJS With jest And TypeScript</title>
		<link>https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/</link>
					<comments>https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/#respond</comments>
		
		<dc:creator><![CDATA[Dawid Sibiński]]></dc:creator>
		<pubDate>Wed, 14 Jul 2021 06:00:00 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jest]]></category>
		<category><![CDATA[mutation tests]]></category>
		<category><![CDATA[software testing]]></category>
		<category><![CDATA[stryker]]></category>
		<category><![CDATA[stryker mutator]]></category>
		<category><![CDATA[strykerjs]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[tests]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://blog.yumasoft.pl/?p=407</guid>

					<description><![CDATA[<p>Continuing the topic of frontend tests with jest, we&#8217;re taking a look at StrykerJS today. Stryker Mutator is one of the most popular tools for mutation testing. We recently struggled with configuring StykerJS to work properly with jest and TypeScript. I&#8217;d like to share our solution to these problems in this article. Jest config First,&#8230;</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/">How To Use StrykerJS With jest And TypeScript</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Continuing <a href="https://blog.yumasoft.pl/2021/07/how-to-configure-jest-tests-on-teamcity/">the topic of frontend tests</a> with <code>jest</code>, we&#8217;re taking a look at StrykerJS today. Stryker Mutator is one of the most popular tools for mutation testing. We recently struggled with configuring StykerJS to work properly with <code>jest</code> and TypeScript. I&#8217;d like to share our solution to these problems in this article.</p>



<span id="more-407"></span>



<h2 class="wp-block-heading">Jest config</h2>



<p>First, make sure that your <a href="https://jestjs.io/docs/configuration"><code>jest</code> configuration</a> is correct. If you&#8217;re with TypeScript (and you <a href="https://blog.yumasoft.pl/2021/06/migrating-javascript-react-app-to-typescript/">should</a> ?), I recommend using <a href="https://www.npmjs.com/package/ts-jest">ts-jest</a> configuration preset. Our config looks as follows:</p>



<script src="https://gist.github.com/dsibinski/04419106e45b2136f63c2255a8a77fba.js"></script>



<p>If everything is fine, you should be able to execute <code>npm test</code> command (assuming it&#8217;s defined in <code>package.json</code> as <code>"test": "jest"</code>) without issues. All your tests should be executed.</p>



<p>We now need to make StrykerJS working with that.</p>



<h2 class="wp-block-heading">StrykerJS with jest configuration</h2>



<p>If you install <a href="https://www.npmjs.com/package/@stryker-mutator/core">StrykerJS</a> as described <a href="https://github.com/stryker-mutator/stryker-js">here</a>, you&#8217;d expect that <code>npx stryker run</code> command runs mutations and everything is just fine. However, if you&#8217;re having wierd issues and errors with that, it probably means that Stryker is not properly configured to execute tests with <code>jest</code>.</p>



<p>When you run <code>npx stryker run</code>, it creates mutants (modifications in your source code) and runs tests against them. It means that StrykerJS must run your tests in the same way you run them. So, if you run tests with <code>jest</code>, Stryker must be able to do the same.</p>



<p>We struggled with many issues related to running StrykerJS with <code>jest</code>. Some of them were related purely to <code>jest</code>, but some of them to TypeScript as well. After numerous trial-and-errors and consulting with StrykerJS community members, we worked out a configuration that finally works fine for us.</p>



<p>Going straight to the point, here&#8217;s the <code>stryker.conf.json</code> file that would make StrykerJS work fine with <code>jest</code> and TypeScript:</p>



<script src="https://gist.github.com/dsibinski/116b47fe141aaf7f71b2e8f1c83137b2.js"></script>



<p>To make it work, install the following npm packages: <a href="https://www.npmjs.com/package/@stryker-mutator/core">@stryker-mutator/core</a>, <a href="https://www.npmjs.com/package/@stryker-mutator/jest-runner">@stryker-mutator/jest-runner</a> and <a href="https://www.npmjs.com/package/@stryker-mutator/typescript-checker">@stryker-mutator/typescript-checker</a>.</p>



<p>Notice few important settings here:</p>



<ul class="wp-block-list"><li> <code>"checkers": ["typescript"]</code> &#8211; this enabled a <a href="https://stryker-mutator.io/docs/stryker-js/typescript-checker/">TypeScript checker</a> plugin, which makes mutations being checked for types before running tests on them. It means that if a mutation introduced by Stryker doesn&#8217;t compile because of types issues, it won&#8217;t be taken into account for mutations (which makes perfect sense)</li><li>&#8220;<code>disableTypeChecks</code>&#8221; &#8211; you still need to tell StrykerJS to not check types when compiling your code with type errors (mutants). It will compile them without types checking, but thanks to TypeScript checker plugin these ones will be filtered out for mutations</li><li><code>"tsconfigFile": "tsconfig.json"</code> &#8211; make sure to point to the TS config file you&#8217;re using here</li><li><code>"concurrency": 4</code>: this is another setting we experimented with to make Stryker working correctly. Without it, we were getting weird errors about lack of memory when running mutations (<code>FATAL ERROR: Committing semi space failed. Allocation failed - JavaScript heap out of memory</code>)</li><li><code>"testRunner": "jest"</code> &#8211; this one enables the <code>jest</code> as our tests runner</li><li><code>"jest"</code> &#8211; here you tell Stryker to use your <code>jest.config.js</code> file we talked about at the beginning</li></ul>



<p>With these settings, I hope that you are able to see this beautiful output of <code>npx stryker run</code> in your console:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" decoding="async" width="827" height="156" src="https://blog.yumasoft.pl/wp-content/uploads/2021/07/Stryker_mutations_result.png" alt="" class="wp-image-414" srcset="https://blog.yumasoft.pl/wp-content/uploads/2021/07/Stryker_mutations_result.png 827w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/Stryker_mutations_result-300x57.png 300w, https://blog.yumasoft.pl/wp-content/uploads/2021/07/Stryker_mutations_result-768x145.png 768w" sizes="auto, (max-width: 827px) 100vw, 827px" /></figure></div>



<h2 class="wp-block-heading">StrykerJS with jest and TypeScript &#8211; summary</h2>



<p>I hope this is helpful for you. StrykerJS is a developing framework, so some things are still hard to figure out. We believe mutation tests are a great way of improving our tests, so we use them on a daily basis. If you ever have any issues with StrykerJS, I encourage you to reach out to <a href="https://join.slack.com/t/stryker-mutator/shared_invite/enQtOTUyMTYyNTg1NDQ0LTU4ODNmZDlmN2I3MmEyMTVhYjZlYmJkOThlNTY3NTM1M2QxYmM5YTM3ODQxYmJjY2YyYzllM2RkMmM1NjNjZjM">the community on Slack</a>. They are extremely helpful there ?</p>
<p>The post <a rel="nofollow" href="https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/">How To Use StrykerJS With jest And TypeScript</a> appeared first on <a rel="nofollow" href="https://blog.yumasoft.pl">Yumasoft</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.yumasoft.pl/2021/07/how-to-use-strykerjs-with-jest-and-typescript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
