<?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 Ferdi Sancak on Medium]]></title>
        <description><![CDATA[Stories by Ferdi Sancak on Medium]]></description>
        <link>https://medium.com/@ferdi_48628?source=rss-b9cae056c25c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jHGmzIlZiuzjwtNNWspSSg.png</url>
            <title>Stories by Ferdi Sancak on Medium</title>
            <link>https://medium.com/@ferdi_48628?source=rss-b9cae056c25c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:59:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ferdi_48628/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[Nx: A Feature-Based Philosophy]]></title>
            <link>https://medium.com/@ferdi_48628/nx-a-feature-based-philosophy-917529204ff6?source=rss-b9cae056c25c------2</link>
            <guid isPermaLink="false">https://medium.com/p/917529204ff6</guid>
            <category><![CDATA[features]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[affected]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[monorepo]]></category>
            <dc:creator><![CDATA[Ferdi Sancak]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 08:02:19 GMT</pubDate>
            <atom:updated>2024-12-03T08:02:19.082Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enhancing the developer experience</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhHusrsv2o0soBgZQumzlQ.png" /><figcaption>ai-generated image of different blocks — representing all different projects and libraries</figcaption></figure><p>Maintaining a scalable and maintainable codebase is crucial for modern development, especially in environments with multiple teams or applications. Nx, a powerful build system for monorepos, offers a philosophy centered around modularity and reusability: <strong>Feature-based libraries, </strong>that simplify application structure and enhance the developer experience. Let’s explore with a simple example.</p><h3>Nx’s Philosophy: Feature-Based Libraries</h3><p>Instead of creating monolithic applications with all functionality in one place, Nx encourages developers to organize the codebase into encapsulated libraries. These libraries house specific features, domains, or utilities, which <em>can</em> be reused across multiple applications. Note that the same benefits apply even if you only use a feature, domain, or utility in one application.</p><p><strong>Why feature-based libraries?</strong></p><ol><li><strong>Modularity: </strong>Each feature exists independently, reducing coupling and improving maintainability.</li><li><strong>Reusability: </strong>Libraries can be shared seamlessly across multiple apps.</li><li><strong>Developer Experience: </strong>A clean separation between features and apps makes the codebase easier to navigate and understand.</li><li><strong>Scalability: </strong>The structure scales effortlessly with growing feature sets and teams.</li><li><strong>Testing: </strong>Isolated features simplify both unit and integration testing.</li></ol><h3>Example: Teams Management Feature</h3><p>Imagine you’re building a project management application with features like <strong>Teams</strong>,<strong> Projects, </strong>and <strong>Dashboard</strong>. Using Nx’s philosophy, your folder structure might look like this:</p><pre>apps<br>  └──project-management<br>      └──src<br>          └──app<br>              ├──teams<br>              │   ├──teams-page.component.ts<br>              │   ├──team-list.component.ts<br>              │   └──team-details.component.ts<br>              └──dashboard/<br>                 └──dashboard-page.component.ts</pre><p>Applying the feature-based libraries philosophy, your folder structure might look more like this:</p><pre>apps<br>  └──project-management<br>      └──src<br>          └──app<br>              ├──teams<br>              │   └──teams-page.component.ts<br>              └──dashboard/<br>                  └──dashboard-page.component.ts<br><br>libs<br>  └──feature-teams<br>      └──src<br>          ├──lib<br>          │  ├──team-list<br>          │  │   └──team-list.component.ts<br>          │  └──team-details/<br>          │      └──team-details.component.ts<br>          └──index.ts</pre><p><strong>Step-by-step guide</strong></p><h4><strong>1. Generate the feature library</strong></h4><p>Use Nx CLI to generate the library for the feature-teams:</p><pre>nx g @nx/angular:library libs/feature-teams --standalone --name feature-teams</pre><p>The --standalone flag ensures the library is generated with standalone components, so no NgModule is created, aligning with Angular’s modern approach.</p><blockquote>Don’t focus too much on where the lib is being generated. When the project scales, you might want to group, move, or rename certain features. In this case Nx has a handy command: nx g move</blockquote><h4><strong>2. Add components to the library</strong></h4><p>To infer the path of the project/library, my preference is to use @schematiccs/angular for generating components, services, and directives:</p><pre>nx g @schematics/angular:component team-list --project feature-teams<br>nx g @schematics/angular:component team-details --project feature-teams</pre><p>These components could look something like this:</p><pre>// team-list.component.ts<br>/** Team List Component **/<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-team-list&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;h2&gt;Teams&lt;/h2&gt;<br>    &lt;ul&gt;<br>      &lt;li *ngFor=&quot;let team of teams&quot;&gt;{{ team.name }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>  `,<br>})<br>export class TeamListComponent {<br>  teams = [<br>    { id: &#39;team1&#39;, name: &#39;Engineering&#39; },<br>    { id: &#39;team2&#39;, name: &#39;Marketing&#39; },<br>    { id: &#39;team3&#39;, name: &#39;Sales&#39; },<br>  ];<br>}</pre><pre>// team-details.component.ts<br>/** Team Details Component **/<br>import { Component, Input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-team-details&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;h3&gt;{{ team.name }}&lt;/h3&gt;<br>    &lt;p&gt;{{ team.description }}&lt;/p&gt;<br>  `,<br>})<br>export class TeamDetailsComponent {<br>  team = input.required&lt;{id: string, name: string, description: string}&gt;()<br>}</pre><h4><strong>3. Use the feature lib in your app</strong></h4><p>There are two ways to use feature library components in your application. You can <strong>a) </strong>import the component directly; which is familiar to most Angular developers, or <strong>b)</strong> create a routed library. How does that work, creating a routed library?</p><p>Let’s keep building upon the example of the project management app where we show a list of teams on a page. In the file structure diagram, this page is called teams-page in the project management app folder. For the sake of the example, let us assume that the only thing teams-page does is render the teams&#39; list component in an &lt;router-outlet&gt; element. This can be skipped entirely by providing a feature-routes object like so:</p><pre>// libs.route.ts<br>/** Routes of Feature Teams Lib **/<br>import { Route } from &#39;@angular/router&#39;;<br>import { TeamListComponent } from &#39;./team-list/team-list.component&#39;;<br>import { TeamDetailsComponent } from &#39;./team-details/team-details.component&#39;;<br><br>export const featureTeamsRoutes: Route[] = [<br>  {<br>    path: &#39;&#39;,<br>    component: TeamListComponent,<br>    children: [<br>      {<br>        path: &#39;:id&#39;,<br>        component: TeamDetailsComponent<br>      }<br>    ]<br>  }<br>]</pre><blockquote>Note! If you choose to expose the components via the route, you should not expose the components independently. This prevents anti-patterns where non-sharable components are shared by accident.</blockquote><p>You can then use the featureTeamsRoutes in your app.routes.ts to lazily load the routes and the components in your app:</p><pre>export const appRoutes: Route[] = [<br>  // ... some routes<br>  {<br>    path: &#39;teams&#39;,<br>    title: &#39;My App | Teams list&#39;,<br>    loadChildren: () =&gt;<br>      import(&#39;@myorg/feature-teams&#39;).then(<br>        (lib) =&gt; lib.featureTeamsRoutes<br>      )<br>  },<br>  // ... some other routes<br>];</pre><h3>The benefits</h3><h4><strong>Nx Tools</strong></h4><p>The dependency graph is one of Nx’s most powerful features. It allows for a visual representation of how libraries and applications interact within the monorepo. This helps manage complex relationships, understand the impact of changes across the codebase, and enhance CI/CD. For example:</p><ul><li>A team can quickly identify dependencies between a library and multiple applications, making it easier to determine how changes to one feature might affect others.</li><li>The graph enables better planning by providing a clear overview of the project’s architecture. This makes your team more predictable.</li></ul><p>Nx has a couple of affected commands which can help you to enhance your CI/CD. By only targeting the libraries or applications impacted by recent changes, they dramatically reduce build and test times. In large projects, this can save a lot of build- and test time. This has a lot of positive side effects: cost reduction, faster feedback cycles, improved developer productivity, and most importantly improved developer experience.</p><p>By creating feature-based libraries, the team can use these tools to its full potential.</p><h4>Scalability</h4><p>Nx’s structure is designed to scale seamlessly with large teams and organizations. By organizing code into modular libraries, Nx supports teams working on different parts of the monorepo simultaneously without conflicts. Teams can focus on their libraries, such as the feature-teams or feature-projects , while maintaining clear boundaries. Each library’s independence ensures that changes in one area do not affect unrelated parts of the codebase.</p><p>This sounds nice, but there are potential pitfalls to consider before you let every team in your organization work within the monorepo. Over-segmenting libraries can lead to unnecessary complexity, where too many small libraries make dependencies harder to track. To avoid this, you could group related functionalities into cohesive libraries. This balances granularity with manageability. In addition, make it a work process to review the dependency graph for every PR to identify overly fragmented libraries and refactor when necessary.</p><h4>Developer Experience</h4><p>A feature-based structure improves the developer experience by simplifying onboarding and day-to-day workflows.</p><p>A modular codebase makes it easier for new team members to locate and understand the code they need to work on. For example, instead of navigating through a monolithic structure, they can focus on a single library like feature-teams and get up to speed quickly.</p><p>Isolated libraries reduce the complexity of debugging and testing. Developers can focus on specific components or services without worrying about the larger application context. In our example, testing the TeamListComponent only requires mock data and does not depend on unrelated parts of the app. This modularity also ensures that bugs in one library do not cascade into others.</p><h3>Let’s wrap it up!</h3><p>Nx’s feature-based philosophy isn’t just about organizing code; it’s about creating a developer experience that prioritizes clarity, modularity, scalability, and efficient CI/CD. By encapsulating features into their own libraries, you can create a clean and maintainable structure, setting your team up for long-term success. Whether you’re building a single app or a suite of applications, this approach ensures your team is predictable, your monorepo efficient, scalable, and a joy to work with.</p><p>And remember: Every commit counts.</p><p>Keep building,<br><strong>Ferdi Sancak</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917529204ff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write a unit test when @angular/fire is involved]]></title>
            <link>https://medium.com/@ferdi_48628/how-to-write-a-unit-test-when-angular-fire-is-involved-6e1fdcad9714?source=rss-b9cae056c25c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e1fdcad9714</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Ferdi Sancak]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 10:13:51 GMT</pubDate>
            <atom:updated>2024-12-02T15:40:56.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A jester setting angular shapes on fire" src="https://cdn-images-1.medium.com/max/1024/1*aaaOeMYvV00FnjrvlJqYmw.png" /><figcaption>A jester setting angular shapes on fire</figcaption></figure><p>Testing Angular services and components interacting with Firebase can be challenging, especially when using the @angular/fire package. This guide will walk you through writing unit tests for a service that utilizes @angular/fire/auth for authentication in an Angular application. We will use Jest as our testing framework, and I will explain each step using a sample AuhtService.</p><h3>The AuthService: An Overview</h3><p>Let’s assume you have an AuthService that provides methods for user authentication, such as logging in, logging out, resetting passwords, and retrieving the user role from the custom claims. This service relies on @angular/fire/auth to interact with Firebase Authentication</p><h4>Setting up the Test Environment</h4><p>Assuming you know how to set up Jest in your angular project, we will focus on how to set up the test environment specifically for the AuthService .</p><p>First, let’s set up our test environment by importing the necessary dependencies and mocking the @angular/fire/auth module.</p><pre>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br>import {<br>  Auth,<br>  signInWithEmailAndPassword,<br>  signOut,<br>  sendPasswordResetEmail,<br>  getIdTokenResult,<br>  user,<br>  User,<br>  UserCredential<br>} from &#39;@angular/fire/auth&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>jest.mock(&#39;@angular/fire/auth&#39;, () =&gt; {<br>  return {<br>    Auth: jest.fn(), // Mock the Auth class<br>    getIdTokenResult: jest.fn(), // Mock the getIdTokenResult function<br>    sendPasswordResetEmail: jest.fn(), // Mock the sendPasswordResetEmail function<br>    signInWithEmailAndPassword: jest.fn(), // Mock the signInWithEmailAndPassword function<br>    signOut: jest.fn(), // Mock the signOut function<br>    user: jest.fn(() =&gt; of(null)), // Mock the user observable, returning a null user by default<br>  };<br>});</pre><p>Explanation:</p><ul><li>jest.mock(&#39;@angular/fire/auth&#39;) : We’re mocking the @angular/fire/auth module, including its Auth class and relevant functions. This allows us to simulate Firebase Authentication behavior without making actual network requests.</li><li>of(null) : The user observable is mocked to return null by default, indicating no user is logged in.</li></ul><h4>Writing the Unit Tests</h4><p>Let’s start with a simple test to verify that our AuthService is correctly instantiated.</p><pre>describe(&#39;AuthService&#39;, () =&gt; {<br>  let service: AuthService;<br>  let authMock: jest.Mocked&lt;Auth&gt;;<br><br>  beforeEach(() =&gt; {<br>    // Mock implementations for the AngularFire functions<br>    (signInWithEmailAndPassword as jest.Mock).mockResolvedValue({} as UserCredential); <br>    (signOut as jest.Mock).mockResolvedValue(undefined);<br>    (sendPasswordResetEmail as jest.Mock).mockResolvedValue(undefined);<br>    (getIdTokenResult as jest.Mock).mockResolvedValue({<br>      claims: {<br>        role: &#39;user&#39;,<br>      },<br>    });<br>    (user as jest.Mock).mockReturnValue(of(null));<br><br>    TestBed.configureTestingModule({<br>      providers: [<br>        AuthService,<br>        { provide: Auth, useValue: {} }, // Provide an empty object as a mock Auth instance<br>      ],<br>    });<br><br>    service = TestBed.inject(AuthService);<br>    authMock = TestBed.inject(Auth) as jest.Mocked&lt;Auth&gt;;<br>  });<br><br>  it(&#39;should be created&#39;, () =&gt; {<br>    expect(service).toBeTruthy();<br>  });<br><br>  it(&#39;should login the user&#39;, async () =&gt; {<br>    const credentials = { email: &#39;test@example.com&#39;, password: &#39;password&#39; };<br>    await service.login(credentials);<br><br>    expect(signInWithEmailAndPassword).toHaveBeenCalledWith(authMock, credentials.email, credentials.password);<br>  });<br><br>  it(&#39;should log out the user&#39;, async () =&gt; {<br>    await service.logout();<br>    expect(signOut).toHaveBeenCalledWith(authMock);<br>  });<br><br>  it(&#39;should send a password reset email&#39;, async () =&gt; {<br>    const email = &#39;test@example.com&#39;;<br>    await service.resetPassword(email);<br>    expect(sendPasswordResetEmail).toHaveBeenCalledWith(authMock, email);<br>  });<br><br>  it(&#39;should retrieve the role from the user token&#39;, async () =&gt; {<br>    (user as jest.Mock).mockReturnValue(of({} as User)); // Mock user observable to return a user<br>    await service[&#39;getRole&#39;](); // You can call private methods this way<br><br>    expect(service.$role()).toBe(&#39;user&#39;);<br>  });<br>});</pre><p>Explanation:</p><ul><li>TestBed.configureTestingModule: We’re configuring the testing module by providing the AuthService and a mock Auth instance.</li><li>authMock: This is a type-safe mock instance of the Auth class, allowing us to control and verify its behavior in tests.</li></ul><blockquote>Sometimes you want to call a private method of a class. In that case, you can use the bracket notation: service[&#39;myPrivateFn&#39;]() which bypasses the visibility constraints private, protected . This should only be allowed for testing or debugging because this can break encapsulation and lead to less maintainable code.</blockquote><h4><strong>Conclusion</strong></h4><p>Unit testing services that interact with Firebase in Angular can seem complex, but by properly mocking the @angular/fire functions, you can create reliable and maintainable tests. This approach ensures that your tests are fast and isolated from external dependencies, making them more robust.</p><p>In this guide, we’ve walked through setting up a test environment, mocking dependencies, and writing unit tests for various methods in an AuthService. These principles can be extended to other services and components in your Angular application, ensuring that your codebase remains stable and well-tested.</p><pre>// full code example:<br><br>import { TestBed } from &#39;@angular/core/testing&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br>import {<br>  Auth,<br>  signInWithEmailAndPassword,<br>  signOut,<br>  sendPasswordResetEmail,<br>  getIdTokenResult,<br>  user, User, UserCredential<br>} from &#39;@angular/fire/auth&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>jest.mock(&#39;@angular/fire/auth&#39;, () =&gt; {<br>  return {<br>    Auth: jest.fn(), // Mock the Auth class<br>    getIdTokenResult: jest.fn(), // Mock the getIdTokenResult function<br>    sendPasswordResetEmail: jest.fn(), // Mock the sendPasswordResetEmail function<br>    signInWithEmailAndPassword: jest.fn(), // Mock the signInWithEmailAndPassword function<br>    signOut: jest.fn(), // Mock the signOut function<br>    user: jest.fn(() =&gt; of(null)), // Mock the user observable, returning a null user by default<br>  };<br>});<br><br><br>describe(&#39;AuthService&#39;, () =&gt; {<br>  let service: AuthService;<br>  let authMock: jest.Mocked&lt;Auth&gt;;<br><br>  beforeEach(() =&gt; {<br>    // Mock implementations for the AngularFire functions<br>    (signInWithEmailAndPassword as jest.Mock).mockResolvedValue({} as UserCredential); // Mock the return value<br>    (signOut as jest.Mock).mockResolvedValue(undefined);<br>    (sendPasswordResetEmail as jest.Mock).mockResolvedValue(undefined);<br>    (getIdTokenResult as jest.Mock).mockResolvedValue({<br>      claims: {<br>        role: &#39;user&#39;,<br>      },<br>    });<br>    (user as jest.Mock).mockReturnValue(of(null)); // Mock the user observable to return null<br><br>    TestBed.configureTestingModule({<br>      providers: [<br>        AuthService,<br>        { provide: Auth, useValue: {} }, // Provide an empty object as a mock Auth instance<br>      ],<br>    });<br><br>    service = TestBed.inject(AuthService);<br>    authMock = TestBed.inject(Auth) as jest.Mocked&lt;Auth&gt;;<br>  });<br><br>  it(&#39;should be created&#39;, () =&gt; {<br>    expect(service).toBeTruthy();<br>  });<br><br>  it(&#39;should login the user&#39;, async () =&gt; {<br>    const credentials = { email: &#39;test@example.com&#39;, password: &#39;password&#39; };<br>    await service.login(credentials);<br><br>    expect(signInWithEmailAndPassword).toHaveBeenCalledWith(authMock, credentials.email, credentials.password);<br>  });<br><br>  it(&#39;should log out the user&#39;, async () =&gt; {<br>    await service.logout();<br>    expect(signOut).toHaveBeenCalledWith(authMock);<br>  });<br><br>  it(&#39;should send a password reset email&#39;, async () =&gt; {<br>    const email = &#39;test@example.com&#39;;<br>    await service.resetPassword(email);<br>    expect(sendPasswordResetEmail).toHaveBeenCalledWith(authMock, email);<br>  });<br><br>  it(&#39;should retrieve the role from the user token&#39;, async () =&gt; {<br>    (user as jest.Mock).mockReturnValue(of({} as User)); // Mock user observable to return a user<br>    await service[&#39;getRole&#39;]();<br><br>    expect(service.$role()).toBe(&#39;user&#39;);<br>  });<br>});</pre><p>And remember: Every commit counts.</p><p>Keep building, <br><strong>Ferdi Sancak</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e1fdcad9714" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>