<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vittorio Guerriero on Medium]]></title>
        <description><![CDATA[Stories by Vittorio Guerriero on Medium]]></description>
        <link>https://medium.com/@vittorioguerriero?source=rss-57ddde6d1e84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Ex6qqd3Q3U1pYeAZiZC_xw.png</url>
            <title>Stories by Vittorio Guerriero on Medium</title>
            <link>https://medium.com/@vittorioguerriero?source=rss-57ddde6d1e84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:38:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vittorioguerriero/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Do you really need to write API Documentation?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cazoo/do-you-really-need-to-write-api-documentation-e44e9685df41?source=rss-57ddde6d1e84------2"><img src="https://cdn-images-1.medium.com/max/1230/1*Vzzilgs63I59C1BoebHUnA.png" width="1230"></a></p><p class="medium-feed-snippet">Use open API specifications as your single source of truth to generate types, validation and documentation</p><p class="medium-feed-link"><a href="https://medium.com/cazoo/do-you-really-need-to-write-api-documentation-e44e9685df41?source=rss-57ddde6d1e84------2">Continue reading on Cazoo Technology Blog »</a></p></div>]]></description>
            <link>https://medium.com/cazoo/do-you-really-need-to-write-api-documentation-e44e9685df41?source=rss-57ddde6d1e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44e9685df41</guid>
            <category><![CDATA[single-source-of-truth]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[schema-first-development]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Vittorio Guerriero]]></dc:creator>
            <pubDate>Thu, 02 Dec 2021 15:18:33 GMT</pubDate>
            <atom:updated>2021-12-07T07:48:29.843Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Jest with ts-auto-mock. Real mocks]]></title>
            <link>https://medium.com/@vittorioguerriero/jest-with-ts-auto-mock-real-mocks-da9a181792dd?source=rss-57ddde6d1e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9a181792dd</guid>
            <dc:creator><![CDATA[Vittorio Guerriero]]></dc:creator>
            <pubDate>Sat, 29 Feb 2020 05:53:42 GMT</pubDate>
            <atom:updated>2020-02-29T05:53:42.020Z</atom:updated>
            <content:encoded><![CDATA[<p>Almost a year back me and my friend Giulio have created a library called <strong>ts-auto-mock</strong>. The library allows you to generate mocks for any typescript types. Here the <a href="https://github.com/Typescript-TDD/ts-auto-mock">github link</a> and <a href="https://typescript-tdd.github.io/ts-auto-mock/">documentation</a></p><p>I’ve decided to write an article specific to <strong>jest</strong> so people can use a <strong>documented guide</strong> to follow when <strong>installing</strong> and <strong>using ts-auto-mock</strong>.</p><blockquote>If you are already familiar with transformers installation just go to the <a href="https://typescript-tdd.github.io/ts-auto-mock/installation#jest--ts-jest--ttypescript"><strong>Installation guide</strong></a><strong> </strong>otherwise just continue reading from here.</blockquote><h3><strong>What is ts auto mock</strong></h3><p><strong>Ts auto mock</strong> take advantages of <em>typescript transformer</em> to enrich your compiled code. You can generate anything you want. There are a lot of cool library that already use this technique and one of them is <strong>ts-auto-mock</strong>.</p><blockquote>Ts auto mock is well explained in <a href="https://medium.com/@vittorioguerriero/typescript-mock-for-real-b15147fddd92">this article</a> but<em> it doesn’t talk about installation and configuration</em> with different testing framework.</blockquote><h3>Installation with Jest</h3><p>First of all. Let’s install some dependencies. I’ve explained next to it why we need them</p><ol><li>Install dependencies</li></ol><pre>npm install jest ts-jest typescript ttypescript jest-ts-auto-mock ts-auto-mock</pre><p><strong>typescript → </strong><em>you wouldn’t be here if you don’t use typescript! Right?</em></p><p><strong>jest → </strong><em>well, you want to use jest, install it, no?</em></p><p><strong>ts-jest</strong> → this will give you 2 things</p><ul><li>typescript compilation to javascript</li><li>allows you to use custom compilers like <strong>ttypescript</strong> that will enable typescript transformer</li></ul><p><strong>ttypescript</strong> → this is a typescript wrapper that enables customer transformer</p><p><strong>ts-auto-mock → </strong>this contains the transformer that creates your mocks</p><p><strong>jest-ts-auto-mock → </strong>this will give you type safety and default mocks for functions (explained later in more details)</p><p><em>After you’ve installed all these dependencies we need to add ts-auto-mock transformer to the list of plugins in the tsconfig.</em></p><p>2. Add the transformer to the <strong>tsconfig.json</strong></p><pre>...<br>&quot;compilerOptions&quot;: {<br>    &quot;plugins&quot;: [<br>      {<br>        &quot;transform&quot;: &quot;ts-auto-mock/transformer&quot;,<br>        &quot;cacheBetweenTests&quot;: false<br>      }<br>    ]<br>...</pre><p>This will run the transformer as part of your typescript compilation</p><p>You can find a <strong>json example</strong> <a href="https://github.com/Typescript-TDD/jest-ts-auto-mock/blob/master/examples/ts-jest-ttypescript/tsconfig.json">here</a></p><blockquote>Remember to set <strong>cacheBetweenTests</strong> to <strong>false</strong> because jest runs test in parallel and ts-auto-mock doesn’t support yet the cache between <strong>parallel</strong> tests</blockquote><p>3. Add ts-jest to the transformation in the jest config</p><p><em>We want to make sure that our typescript files are compiled by ts-jest.</em></p><pre>...<br> &quot;jest&quot;: {<br>    &quot;transform&quot;: {<br>        &quot;.(ts|tsx)&quot;: &quot;ts-jest&quot;<br>    }<br>  }<br>...</pre><blockquote><em>This configuration can be added in your jest package json or in your jest.config.js</em></blockquote><p>You can find a <strong>json example</strong> <a href="https://github.com/Typescript-TDD/jest-ts-auto-mock/blob/master/examples/ts-jest-ttypescript/package.json">here</a></p><p>4. Set <strong>ttypescript</strong> (NOT TYPESCRIPT, <strong>TTYPESCRIPT</strong>) as compiler</p><pre>...<br>&quot;jest&quot;: {<br>    &quot;globals&quot;: {<br>      &quot;ts-jest&quot;: {<br>        &quot;compiler&quot;: &quot;ttypescript&quot;<br>      }<br>    }<br>}<br>...</pre><blockquote><em>This configuration can be added in your jest package json or in your jest.config.js</em></blockquote><p>You can find a <strong>json example</strong> <a href="https://github.com/Typescript-TDD/jest-ts-auto-mock/blob/master/examples/ts-jest-ttypescript/package.json">here</a></p><p>5. Init jest-ts-auto-mock</p><p>The last step before start writing our tests is to add jest-ts-auto-mock to the setup files. This part is required to define your <strong>default custom mock</strong> that will replaces methods/functions (<strong>jest.fn</strong>)</p><ul><li>Create a config.ts file</li></ul><pre>import &quot;jest-ts-auto-mock&quot;;</pre><ul><li>Add the file in the setup files</li></ul><pre>...<br>&quot;jest&quot;: {<br>    &quot;setupFiles&quot;: [<br>      &quot;&lt;rootDir&gt;config.ts&quot;<br>    ]<br> }<br>...</pre><p><strong>setupFiles</strong> will allow you to run a file before each test. It will default your functions mocks to jest.fn. You can see it <a href="https://github.com/Typescript-TDD/jest-ts-auto-mock/blob/master/index.ts">here</a></p><blockquote><em>This configuration can be added in your jest package json or in your jest.config.js</em></blockquote><p><strong>Note</strong>: you <strong>don’t have to</strong> import and install jest-ts-auto-mock. You can just copy the content from the link above and personalise your default function mocks.</p><p>6. Create a test</p><pre>import { createMock } from &quot;ts-auto-mock&quot;;<br><br>interface Interface {<br>   a: string;<br>   b: number;<br>}<br><br>describe(&#39;a mock that&#39;, () =&gt; {<br>   let mock: Interface;<br><br>   beforeEach(() =&gt; {<br>      mock = createMock&lt;Interface&gt;();<br>   });<br><br>   it(&#39;should work&#39;, () =&gt; {<br>      expect(mock.a).toBe(&quot;&quot;);<br>   });<br>});</pre><p>7. Run your test</p><pre>//package.json<br>...<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;jest&quot;<br>  }<br>...</pre><pre>npm run test</pre><p>All done!!!</p><p>If you are interested in more configuration you can visit this <a href="https://typescript-tdd.github.io/ts-auto-mock/installation">link</a></p><h3><strong>Thanks</strong></h3><p>Thanks to the people that are using the library that kind of pushed me to write this article. Installing a transformer is painful.</p><p>Thanks again to Giulio to keep fixing bugs and improving ts-auto-mock</p><h3><strong>Links</strong></h3><ul><li><a href="http://typescript-tdd.github.io/ts-auto-mock/">ts-auto-mock</a></li><li><a href="https://github.com/Typescript-TDD/jest-ts-auto-mock">jest-ts-auto-mock</a></li><li><a href="https://github.com/Typescript-TDD/ts-auto-mock">github</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9a181792dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion in React — Part 2]]></title>
            <link>https://medium.com/@vittorioguerriero/dependency-inversion-in-react-part-2-2fcad804288?source=rss-57ddde6d1e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fcad804288</guid>
            <dc:creator><![CDATA[Vittorio Guerriero]]></dc:creator>
            <pubDate>Tue, 29 Oct 2019 08:37:31 GMT</pubDate>
            <atom:updated>2019-10-29T08:37:31.658Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve recently written an article about <strong>dependency inversion</strong> in React and how to respect it using <strong>React.Context</strong> to hide implementation details.</p><p>Here the link — <a href="https://medium.com/@vittorioguerriero/dependency-inversion-in-react-58f1545dc039">Dependency Inversion in React</a></p><p>If you are implementing the design explained in the article you will have something like this:</p><pre><strong>function </strong>MyComponent() {<br> <strong>const </strong>context: AppContext = React.useContext(APP_CONTEXT);<br> <strong>const </strong>http: IHttp = context.http;</pre><pre> ... <br> return &lt;div&gt;...&lt;/div&gt;<br>}</pre><p>I want to be honest, I don’t like this design or at least I don’t like a part of it, I want to improve it. Let’s see why.</p><p>This component <strong>doesn’t know which HTTP</strong> is using → this is <em>GREAT</em> 💪💪💪</p><p><strong>But It knows knows about all the abstractions inside the context</strong>. → 😭😭😭. That means that every time you need one dependency from your context you will import all the dependencies…</p><blockquote>The component will have access to the <strong>entire ioc container</strong> when mostly of the time it needs just a <strong>part</strong> of it.</blockquote><p>How do we solve this? How do we make sure that the component will receive/use <strong>only what it needs so we can re use it?</strong></p><h3>react-connect-ctx</h3><p>I’ve created this small utility that will “inject” only what you need from a context.</p><p>I wanted to call it react-connect-context but all the names were already taken in npm registry 😭</p><p>The purpose of this library is pretty <em>simple</em>.</p><blockquote>Connect a component to a context or a part of it.</blockquote><h4>This is the API</h4><pre><em>connectContext</em>(<strong><em>CONTEXT</em></strong>)(<strong><em>Component</em></strong>, <strong>mapContextToProps</strong>);</pre><p>There are few keywords important here</p><ul><li><strong><em>CONTEXT</em></strong></li><li><strong><em>Component</em></strong></li><li><strong><em>mapContextToProps</em></strong></li></ul><p>Let’s analyze one by one</p><h4><strong>CONTEXT</strong></h4><p>This is the actual React.Context that you create</p><pre><strong>export interface </strong>IService {<br>    getName(): <strong>string</strong>;<br>}<br><br><strong>export interface </strong>Context {<br>    service: IService;<br>}<br><br><strong>export class Service implements </strong>IService {<br>    getName(): <strong>string </strong>{ <strong>return </strong>&#39;a name&#39;; }<br>}</pre><pre><strong>export const <em>CONTEXT</em></strong>: React.Context&lt;Context&gt; = React.<em>createContext</em>&lt;Context&gt;({<br>    service: <strong>new Service</strong>()<br>});</pre><h4>Component</h4><p>This is the component that needs one of the context dependency</p><pre><strong>export interface </strong>ComponentProps {<br>    service: IService;<br>}<br><strong>export function </strong><em>Component</em>(props: ComponentProps) {<br>    <strong>return </strong>&lt;<strong>div</strong>&gt;Hello {props.service.getName()}&lt;/<strong>div</strong>&gt;;<br>}</pre><h4>MapComponentToProps</h4><p>This is the function that will decide which dependencies from the context needs to be assigned to the component (it works similar to <em>redux connect</em>)</p><pre><strong>function </strong>mapContextToProps(context: Context) {<br>    <strong>return </strong>{<br>        service: context.service<br>    }<br>}</pre><p>Let’s see a full example (it can be found in the github repository with all the files nicely divided) — <a href="https://github.com/uittorio/react-connect-ctx/tree/master/docs/example">Here</a></p><h4>you need to install it (nothing to explain here)</h4><pre>npm i react-connect-ctx -D</pre><h4>2. you need a React.Context</h4><pre><em>export const APP_CONTEXT: React.Context&lt;AppContext&gt; = React.createContext(null);</em></pre><p>You don’t need to create a context with null value, you can directly assign what the context would it be. I prefer this solution because it allows me to completely detach the connection between React and the actual values that you pass in the context</p><h4>3. Lets populate the context</h4><pre><em>interface IPersonService {<br>  getName(personId: string): Promise&lt;string&gt;;<br>}<br><br>interface AppContext {<br>  personService: IPersonService;<br>}<br><br>function personService(): IPersonService {<br>  return {<br>    getName(id: string): Promise&lt;string&gt; {<br>      return Promise.resolve(&quot;A name&quot;);<br>    }<br>  }<br>}<br><br>export const appDependencies: AppContext = {<br>  personService: personService()<br>}</em></pre><pre><em>export function App() {<br>    return &lt;APP_CONTEXT.Provider value={appDependencies}&gt;<br>        &lt;PersonWrapperComponent/&gt;<br>    &lt;/APP_CONTEXT.Provider&gt;<br>}</em></pre><p>Okay, few things we are doing</p><ul><li>defining a personService</li><li>adding the personService to the appContext</li><li>providing values to the APP_CONTEXT</li></ul><h4>4. Lets create a component that will use personService</h4><pre><em>interface PersonComponentProps {<br>  personService: IPersonService;<br>  id: string;<br>}<br><br>function PersonComponent(props: PersonComponentProps) {<br>  const [name, setName] = React.useState(&quot;&quot;);<br><br>  const getName = async() =&gt; {<br>    const newName = await props.personService.getName(props.id);<br>    setName(newName);<br>  };<br><br>  return &lt;&gt;<br>    &lt;button onClick={getName}&gt;Load details&lt;/button&gt;<br>    &lt;p&gt;{name}&lt;/p&gt;<br>  &lt;/&gt;<br>}</em></pre><p>This component will be responsible to retrieve person information given a specific Id. We need to give to this component a personService and a person id</p><h4>5. Let’s give to the personComponent the personService</h4><pre><strong>import </strong>{ <em>connectContext </em>} <strong>from </strong>&#39;react-conntext-ctx&#39;;</pre><pre><strong>function </strong>mapContextToProps(context: AppContext) {<br>    <strong>return </strong>{<br>        personService: context.personService<br>    }<br>}<br><br><strong>export const <em>PersonComponentHOC </em></strong>= connectContext(<strong><em>APP_CONTEXT</em></strong>)(PersonComponent, mapContextToProps);</pre><p>Thats it! Now you have a component that has only the personService, its still benefit from using React.Context but not depending directly</p><h4>6. Final stage — Use it and provide the id</h4><pre><strong>export function </strong><em>PersonWrapperComponent</em>() {<br>    <strong>return </strong>&lt;<strong><em>PersonComponentHOC</em> </strong>id=&#39;123&#39;/&gt;<br>}</pre><p>Benefit:</p><ul><li>Your component <strong>will know</strong> only about what he <strong>needs</strong></li><li>The component is <strong>completely detach</strong> from React context so its more <strong>reusable</strong></li><li><strong>Type safe</strong></li><li><strong>Unit test</strong> will be <strong>easier</strong></li></ul><p>Links:</p><ul><li><a href="https://github.com/uittorio/react-connect-ctx">react-connect-ctx</a></li><li><a href="https://medium.com/@vittorioguerriero/dependency-inversion-in-react-58f1545dc039">Dependency Inversion in React</a></li><li><a href="https://github.com/uittorio/react-connect-ctx/tree/master/docs/example">Full Example</a></li></ul><p>If you reach this point you would think that this implementation is really long and requires a lot of code, it looks like that but in reality I’ve just divided classes, interfaces in different files :). So, don’t get scared, and try it!! Let me know what you think</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fcad804288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Inversion in React]]></title>
            <link>https://medium.com/@vittorioguerriero/dependency-inversion-in-react-58f1545dc039?source=rss-57ddde6d1e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/58f1545dc039</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[dependency-inversion]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vittorio Guerriero]]></dc:creator>
            <pubDate>Fri, 19 Apr 2019 17:59:13 GMT</pubDate>
            <atom:updated>2022-08-06T10:23:34.126Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using React Context</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fyi6tb4jxYiWRIYGtEb0A.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@jenna-hamra-248942?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Jenna Hamra</a> from <a href="https://www.pexels.com/photo/reflection-of-finger-in-a-mirror-804416/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Dependency inversion is satisfied by using <strong>interfaces </strong>in dependencies.</p><pre><strong>interface </strong>CoffeeMachine {<br>  expresso(): <strong>void</strong>;<br>}<br><br><strong>function </strong><em>CoffeeShop</em>(coffeeMachine: CoffeeMachine) {<br>  <strong>return </strong>{<br>    expresso: () =&gt; {<br>      coffeeMachine.expresso();<br>    }<br>  }<br>}</pre><p>In this example we simply create a CoffeeShop that can make an espresso, the coffee machine <strong>implementation can be changed</strong> with another implementation and the <strong>CoffeeShop would not know the difference.</strong></p><p>When I started developing in React I’ve found a lot of example online using concrete implementation directly inside a component.</p><pre><strong>import </strong>axios <strong>from </strong>&quot;axios&quot;;<br><strong>import </strong>* <strong>as </strong>React <strong>from </strong>&quot;React&quot;;</pre><pre><strong>function </strong><em>PostComponent</em>() {<br>  <strong>const </strong>[post, setPost] = React.<em>useState</em>(<strong>null</strong>);<br><br>  axios.get(`url`).then(res =&gt; {<br>    setPost(res.data);<br>  })<br><br>  <strong>return </strong>post &amp;&amp; &lt;<strong>div</strong>&gt;<br>    {post.title}<br>  &lt;/<strong>div</strong>&gt;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*SSRR37gEUbdsChDHT8y9uQ.png" /></figure><p>This component <strong>is depending on axios</strong>. How do we refactor this code to follow the dependency inversion principle?</p><h4>What if we just wrap axios in a http function?</h4><pre><strong>import </strong>axios <strong>from </strong>&quot;axios&quot;;</pre><pre><strong>function </strong><em>Http</em>() {<br>    <strong>return </strong>{<br>        get: <strong>async</strong>&lt;T&gt;(url: <strong>string</strong>): Promise&lt;T&gt; =&gt; {<br>            <strong>return </strong>axios.get(url).then(data =&gt; data.data);<br>        }<br>    }<br>}</pre><p>And now the component will import http.</p><pre><strong>import { http } from </strong>&#39;./http&#39;;</pre><pre><strong>function </strong><em>PostComponent</em>() {</pre><pre>http().get(&quot;url&quot;).then(...<br>...<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*5NdJ7a-Qvbsdxa10BK6Pmw.jpeg" /></figure><p>As you can see PostComponent is still depending indirectly on axios. So you don’t really depend on an abstraction.</p><p>What we really want is to make sure PostComponent <strong>does not</strong> depend on axios directly (see the image below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*EfLAYsvcsDFC_xMv2m7G6w.png" /></figure><ul><li>Post Component depends on IHttp</li><li>Http implements IHttp and depends on axios</li><li>Post Component <strong>does not depend</strong> on either axios or http</li></ul><p>We could create a wrapper of axios and pass it in the parameters of the component as interface</p><h4>Yes. Let’s do it.</h4><h4>1 — Create the interface IHttp</h4><p><em>http.interface.ts</em></p><pre><strong>interface </strong>IHttp {<br>    get&lt;T&gt;(url: <strong>string</strong>): Promise&lt;T&gt;;<br>}</pre><h4>2 — Http Implement the interface</h4><p><em>http.ts</em></p><pre><strong>import </strong>axios <strong>from </strong>&quot;axios&quot;;</pre><pre><strong>function </strong><em>Http</em>(): IHttp {<br>    <strong>return </strong>{<br>        get: <strong>async</strong>&lt;T&gt;(url: <strong>string</strong>): Promise&lt;T&gt; =&gt; {<br>            <strong>return </strong>axios.get(url).then(data =&gt; data.data);<br>        }<br>    }<br>}</pre><h4>3 — Pass IHttp to the component</h4><pre><strong>import </strong>{ APP_CONTEXT } <strong>from </strong>&#39;./context&#39;;<br><strong>import </strong>{ Http } <strong>from </strong>&#39;./http&#39;;<br><strong>import </strong>{ IHttp } <strong>from </strong>&#39;./http.interface&#39;;<br><strong>import </strong>{ appDependencies } <strong>from </strong>&#39;./dependencies&#39;;<br>const http: IHttp = Http();</pre><pre><strong>export function </strong><em>App</em>(): JSX.Element {<br>  <strong>return </strong>(   <br>     &lt;<strong>PostComponent http={http}</strong>/&gt;        <br>  );<br>}</pre><p>As you can see PostComponent does not depend on axios! Yuppieeee</p><pre><strong>import </strong>{ IHttp } <strong>from </strong>&#39;./http.interface&#39;;</pre><pre><strong>function </strong><em>PostComponent</em>({http: IHttp}) {<br>...<br>}</pre><p>This is perfect when your application is really small.</p><p>What if there are another 4–5 components between App and PostComponent? Do we move the dependency to the closest component? Why should the closest component know about http?</p><p>Ideally we want to create the http implementation at the app level because in the future it will require more configuration and we want to create it once. We don’t want to spread this implementation around the app.</p><p>So, what we do?</p><h3>We could use React.Context!</h3><p>In react we have the Context API that can be used as a Service Locator</p><h4>1 — Create your context as null and define the interface</h4><p><em>context.ts</em></p><pre><strong>import </strong>{ IHttp } <strong>from </strong>&#39;./http.interface&#39;;</pre><pre><strong>export const </strong>APP_CONTEXT: React.Context&lt;AppContext&gt; = React.<em>createContext</em>(<strong>null</strong>);<br><br><strong>export interface </strong>AppContext {<br>  http: IHttp;<br>}</pre><h4>2 — Create your dependencies initialisation</h4><p><em>dependencies.ts</em></p><pre><strong>import </strong>{ IHttp } <strong>from </strong>&#39;./http.interface&#39;;<br><strong>import </strong>{ Http } <strong>from </strong>&#39;./http&#39;;</pre><pre><strong>const </strong>http: IHttp = <em>Http</em>();</pre><pre><strong>export const </strong>appDependencies: AppContext = {<br>  http: http<br>}</pre><h4>3 — Add the context to your app</h4><pre><strong>import </strong>* <strong>as </strong>React <strong>from </strong>&quot;React&quot;;<br><strong>import </strong>{ APP_CONTEXT } <strong>from </strong>&#39;./context&#39;;<br><strong>import </strong>{ appDependencies } <strong>from </strong>&#39;./dependencies&#39;</pre><pre><strong>export function </strong><em>App</em>(): JSX.Element {<br>  <strong>return </strong>(<br>      &lt;<strong>APP_CONTEXT.Provider </strong>value={appDependencies}&gt;<br>        &lt;PostComponent/&gt;<br>      &lt;/<strong>APP_CONTEXT.Provider</strong>&gt;<br>  );<br>}</pre><h4>4 — Use it in PostComponent</h4><pre><strong>import </strong>* <strong>as </strong>React <strong>from </strong>&quot;React&quot;;<br><strong>import </strong>{ APP_CONTEXT } <strong>from </strong>&#39;./context&#39;;</pre><pre><strong>function </strong><em>PostComponent</em>() {<br>  <strong>const </strong>http: IHttp = React.<em>useContext</em>(APP_CONTEXT).http;<br>  <strong>const </strong>[post, setPost] = React.<em>useState</em>(<strong>null</strong>);<br>  <br>  http.get(`url`).then(res =&gt; {<br>    setPost(res.data);<br>  })<br><br>  <strong>return </strong>post &amp;&amp; &lt;<strong>div</strong>&gt;<br>    {post.title}<br>  &lt;/<strong>div</strong>&gt;<br>}</pre><h4>Done.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*v7slZlwehXCkE_wx-TiqDg.png" /></figure><ul><li>PostComponent depends on AppContext, so on IHttp</li><li>AppDependencies implements the AppContext and depends on Http, so on Axios</li></ul><p>What is the benefit of creating and developing your application with this approach? React context allows you to take advantage of dependency inversion. You can provide a different implementation of the same interface</p><pre><strong>export function </strong><em>App</em>() {<br>  <strong>return </strong>(<br>      &lt;<strong>POST_CONTEXT.Provider </strong>value={dependenciesA}&gt;<br>        &lt;<strong>PostComponent</strong>/&gt;<br>      &lt;/<strong>POST_CONTEXT.Provider</strong>/&gt;<br><br>      &lt;POST_CONTEXT.Provider value={dependenciesB}&gt;<br>        &lt;PostComponent/&gt;<br>      &lt;/POST_CONTEXT.Provider/&gt; <br>        <br>      &lt;POST_CONTEXT.Provider value={dependenciesC}&gt;<br>        &lt;PostComponent/&gt;<br>      &lt;/POST_CONTEXT.Provider/&gt;<br>  );<br>}</pre><h3>Conclusions</h3><h4>Benefits</h4><ol><li>This solution will respect <strong>dependency inversion principle</strong></li><li><strong>Unit test</strong> will be easier</li><li>Components <strong>are not coupled</strong> to core libraries</li><li>Switching dependencies is efficient</li></ol><h4>Disadvantages</h4><ol><li>The creation of dependencies has to be done manually, you don’t have IOC (Inversion of Control)</li></ol><p>Thanks to Giulio that helped me understand the differences between IOC, DI (Dependency Injection) and DIP (Dependency Inversion Principle)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58f1545dc039" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript Mock… for real]]></title>
            <link>https://medium.com/@vittorioguerriero/typescript-mock-for-real-b15147fddd92?source=rss-57ddde6d1e84------2</link>
            <guid isPermaLink="false">https://medium.com/p/b15147fddd92</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[jasmine]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Vittorio Guerriero]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 16:49:24 GMT</pubDate>
            <atom:updated>2019-04-14T16:50:27.343Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typescript Types Mock… for real</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWYm3Dm7s0t8lLWYRW4pow.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@kevin-ku-92347?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Kevin Ku</a> from <a href="https://www.pexels.com/photo/coding-computer-data-depth-of-field-577585/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h4>Mocking <strong>interfaces/classes</strong> in your unit test could be <strong>annoying</strong>.</h4><p>You often need to create your mock version and end up with <strong>a lot</strong> of mock object data in your test.</p><h3>😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭😭</h3><h4>Problem</h4><p>We have a simple person interface that is being used by a function that returns some of the information…</p><pre><strong>interface </strong>Person {<br>    id: <strong>string</strong>;<br>    getName(): <strong>string</strong>;<br>    getAge(): <strong>number</strong>;<br>    getChildren(): Person[];<br>}</pre><pre><strong>function </strong><em>PersonInformation</em>(person: Person): <strong>string </strong>{<br>    <strong>return </strong>`id=${person.id} - name=${ person.getName()}&#39;;<br>}</pre><p>…in your test you need to provide a person object with methods that satisfy the interface completely unless you use casting (you are <strong>evil</strong> 😈 ).</p><p>Even with casting you need to provide the implementation of methods and properties that you need for the test.</p><pre><strong>const </strong>mockPerson: Person = {<br>    id: &#39;&#39;,<br>    getName: () =&gt; &#39;&#39;,<br>    getAge: () =&gt; 0,<br>    getChildren: () =&gt; [],<br>};</pre><pre>const personInformation: string = <em>PersonInformation(mockPerson);</em></pre><pre>personInformation// &#39;id=&quot;&quot; - name=&quot;&quot;&#39;</pre><p>Typescript <strong>doesn’t keep interfaces</strong> after compilation so it’s not possible to create basic mocks from interfaces without giving them an implementation</p><p>What if there was a way to generate mocks from interface to make test development faster and nicer?</p><p>If I was creating a mock of Person from my imaginary mock creator I would like to automatically have the minimum default implementation like this example</p><pre>const mock: Person = myImaginaryMockCreator&lt;Person&gt;();<br>mock.id // &quot;&quot;<br>mock.getName() // &quot;&quot;<br>mock.getAge // 0<br>mock.getChildren() // []</pre><h3>🤑</h3><p>If I had this functionality at least my test would not fail for <strong>missing implementation</strong></p><h3>Is this a dream?? No</h3><h4>Solution</h4><p>How do we <strong>improve</strong> our test? How do we <strong>automate</strong> our <strong>mocks</strong> so we can concentrate on the test instead of the mock objects?</p><h3>There is a solution, and its called <strong>ts-auto-mock </strong>💪</h3><h3>Ts-auto-mock</h3><p>The intention of Ts-auto-mock is to create mocks from types. It doesn’t want to replace your test framework.</p><p>It’s a library that takes advantages of typescript transformer and it creates mocks for you. Let’s have a look of a basic usage and then we will talk about installation</p><pre>import { createMock } from &#39;ts-auto-mock&#39;;</pre><pre>const mock: Person = createMock&lt;Person&gt;();</pre><p>Done. You call createMock with any type and it will create a basic mock with default values.</p><h3>Installation</h3><ol><li><strong>install ts-auto-mock</strong></li></ol><p>Simple as npm install ts-auto-mock -D -E</p><p>2. <strong>Add the transformer ts-auto-mock/transformer to your compilation</strong></p><p>This part is a bit tricky but there are different solutions based on what you are using. <a href="https://github.com/uittorio/ts-auto-mock/blob/HEAD/docs/TRANSFORMER.md">link</a></p><p>For the purpose of this article I’m not going to explain how to configure it in depth, hence I will assume that the transformer is already part of the compilation</p><h3>Usage</h3><pre>import { createMock } from &#39;ts-auto-mock&#39;;</pre><pre>const mock: Person = createMock&lt;Person&gt;();</pre><p>createMock will create automatically:</p><ol><li>Object properties</li><li>Methods properties</li><li>Nested objects</li></ol><p>If you have a recursive interface ts-auto-mock will make sure that the nested object is always present</p><pre><strong>interface </strong>Employee {<br>    position: string;<br>    boss: Employee<br>};</pre><pre>const mock: Employee = createMock&lt;Employee&gt;();</pre><pre>mock.boss.boss.boss.boss........... // It will not fail. It exists </pre><p>This is the basic feature of ts-auto-mock. The library goes a bit <strong>further</strong>.</p><h3>Extensions</h3><p>Mostly of the time you will have your framework (jasmine, jest, aNewBeautifulTestFramework, etc ).</p><p>There are already two libraries that extends ts-auto-mock:</p><ul><li><a href="https://github.com/uittorio/jest-ts-auto-mock"><strong>jest-ts-auto-mock</strong></a></li><li><a href="https://github.com/uittorio/jasmine-ts-auto-mock"><strong>jasmine-ts-auto-mock</strong></a>.</li></ul><p>You can use them and follow their documentation.</p><blockquote>If you want to understand how the extension works keep reading…</blockquote><p><strong>ts-auto-mock </strong>expose a factory where we can decide what it will happened every time it finds a method</p><h4>Configure your mock</h4><p>If we want to have a jasmine.Spy instead of the default method, we can configure ts-auto-mock to do it (this is what jasmine-ts-auto-mock and jest-ts-auto-mock do)</p><p><em>Note: This file needs to run before your tests.</em></p><pre><strong>import </strong>{ <strong>MockFactory </strong>} <strong>from </strong>&#39;ts-auto-mock&#39;;</pre><pre><strong>MockFactory</strong>.<em>instance</em>.registerFactory((name: <strong>string</strong>, value: <strong>any</strong>) =&gt; {</pre><pre><strong>  return </strong>jasmine.<em>createSpy</em>(name).and.returnValue(value);</pre><pre>});</pre><h4>Provide your return type</h4><pre><strong>declare module </strong>&#39;ts-auto-mock&#39; {<br><strong>  interface </strong>MockMethod&lt;TR&gt; <strong>extends </strong>jasmine.Spy<br>}</pre><h4>Get the mock safely</h4><p>The spy method exists inside the mock object but ts-auto-mock wants to be <strong>type safe</strong> and makes sure that you have a clear division between the instance of the mock (Person) and the customised mocked version.</p><p>Ts-auto-mock provide a small utility to get your functionality.</p><p><strong><em>— — — — — — — — With a string- — — — — — — —</em></strong></p><pre><strong>import </strong>{ <em>On, method </em>} <strong>from </strong>&#39;ts-auto-mock&#39;;</pre><pre><strong>let </strong>nameSpy = <em>On</em>(mockPerson).get(<em>method</em>(&#39;getName&#39;));</pre><p><strong><em>— — — — — — — -With method selection — — — — — — —</em></strong></p><pre><strong>import </strong>{ <em>On, method </em>} <strong>from </strong>&#39;ts-auto-mock&#39;;</pre><pre>nameSpy = <em>On</em>(mockPerson).get(<em>method</em>(mock =&gt; mock.getName));</pre><p>Done.</p><p>Now if we test again our methods we can get the spies</p><pre><strong>import </strong>{ <em>createMock, On, method </em>} <strong>from </strong>&#39;ts-auto-mock&#39;;</pre><pre><strong>interface </strong>Person {<br>    getName(): <strong>string</strong>;<br>    getSurname(): <strong>string</strong>;<br>}<br><br><strong>function </strong><em>personFullName</em>(person: Person): <strong>string </strong>{<br>    <strong>return </strong>person.getName() + person.getSurname();<br>}</pre><pre>const mock: Person = createMock&lt;Person&gt;();<br>const nameSpy: jasmine.Spy = On(mock).get(method(&#39;getName&#39;));<br>const surnameSpy: jasmine.Spy = On(mock).get(method(&#39;getSurname&#39;));</pre><pre>personFullName(person);// &quot;&quot;<br>expect(nameSpy).toHaveBeenCalled();<br>expect(surnameSpy).toHaveBeenCalled();</pre><h3><strong>Conclusion</strong></h3><p>Ts-auto-mock has few benefits:</p><ul><li>Real mocks types</li><li>Less code in your unit test</li><li>Recursive mocks</li><li>Can be extended. Is not coupled to a specific testing framework</li></ul><p>The main disadvantages is the <strong>configuration </strong>that hopefully will be solved once Typescript <a href="https://github.com/Microsoft/TypeScript/issues/14419">will add support</a> for custom plugin directly in the tsconfig.</p><h3>About the library</h3><p>These libraries have been created by me and <strong>Giulio Caprino</strong>. (It wouldn’t be possible without him).</p><p>We are planning to add new feature to this library to improve performance and more automatic custom mocks</p><p>Also I would like to thanks the creator of <a href="https://github.com/kimamula/ts-transformer-keys#readme">ts-transformers-keys</a>. I’ve used his library for the first couple of days to understand a bit more on how to create a typescript transformer</p><p>Another special thanks to the creator of <a href="https://github.com/cevek/ttypescript">ttypescript</a>. Thanks to his library jest-ts-auto-mock can be used with a rather easy configuration along jest</p><h3>Links</h3><ul><li><a href="https://github.com/uittorio/ts-auto-mock">ts-auto-mock</a></li><li><a href="https://github.com/uittorio/jest-ts-auto-mock">jest-ts-auto-mock</a></li><li><a href="https://github.com/uittorio/jasmine-ts-auto-mock">jasmine-ts-auto-mock</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b15147fddd92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>