Friday, March 16, 2018

Testing Angular Components That Use Pipes

Pipes are a common feature in Angular that are often used to do things like format data (read more about Pipes in the Angular documentation). Unfortunately, when we use Pipes in our Components they can cause some issues with testing. In order to test a Component that uses a Pipe you need to either bring the Pipe in to the TestBed or (my preference) create a Fake Pipe and instruct your test to use that instead.

I prefer this method because it means I can control the functionality of the Pipe, which usually means replacing whatever the Pipe actually does with nothing. I can also more easily manipulate my tests to provide expected outputs, which is always helpful.

Let's say you have a Component whose template uses a Pipe to translate something. The real TranslatePipe accepts a parameter called "query", looks up the query value in a file, and returns the value found in the file. It's basically a key/value lookup. When we're unit testing we want to make sure we're testing the smallest possible unit, which means we should have already tested the real TranslatePipe. Since we can trust that the real TranslatePipe works as expected, we don't want to actually use the TranslatePipe in our Component tests. Instead we'll create a fake TranslatePipe.

When we use the Angular CLI to generate our components we also get a spec file for that component, which has some boilerplate code in it that probably looks something like this:
/* Import statements up here */

describe('CoolComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [CoolComponent]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoolComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Let's say the very first thing we're going to do on our CoolComponent is use our TranslatePipe to display a title on the page. We know the title of the page will need to be translated and we know we have the TranslatePipe. What we'll want to test is whether the TranslatePipe is invoked during rendering.
it('should display translated title', () => {});
Before we can actually write our test we'll need to create our FakeTranslatePipe and instruct the TestBed to use it instead of the real TranslatePipe. In the same file*, before the describe block, but after the imports, add the following code:
@Pipe({name: 'translate'})
export class FakeTranslatePipe implements PipeTransform {
  transform(query: string): any {
    return 'Translated!';
  }
}
Now that we've created the FakeTranslatePipe, we'll instruct the TestBed to use it by supplying it to the declarations array. The updated beforeEach looks like this:
beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      CoolComponent,
      FakeTranslatePipe
    ]
  })
  .compileComponents();
}));
When our component markup uses the translate pipe, our FakeTranslatePipe will be used instead of the real TranslatePipe. That's all we have to do to avoid an error, but if we want to test whether the Pipe was actually invoked during rendering we'll need to create a spy on it. Create a variable for the spy inside the describe block, but outside the first beforeEach.
let pipeSpy: jasmine.Spy;
After we compile the components, but while we're still inside the first beforeEach, we'll spy on FakeTranslatePipe's translate function. Because we're spying on a function that exists on a class instead of an instance we'll have to spy on the prototype of FakeTranslatePipe. It's easy enough to do once you know to do it. The spy creation looks like this:
pipeSpy = spyOn(FakeTranslatePipe.prototype, 'transform').and.callThrough();
Now we can treat pipeSpy like other spy (that is, we can check whether it was called, how many times, with what parameters, etc.) in our tests. Here's what our test might look like now:
it('should display translated title', () => {
  expect(pipeSpy).toHaveBeenCalledTimes(1);
  expect(pipeSpy).toHaveBeenCalledWith('page-title');
});
We're really close to being finished, but all we know is that our FakeTranslatePipe was invoked. We don't know whether we put the result in an h1 tag. We can add that to our test so the end result looks like this:
it('should display translated title', () => {
  const debugElements = fixture.debugElement.queryAll(By.css('h1'));

  expect(debugElements.length).toBe(1);
  expect(debugElements[0].nativeElement.textContent).toBe('Translated!');
  expect(pipeSpy).toHaveBeenCalledTimes(1);
  expect(pipeSpy).toHaveBeenCalledWith('page-title');
});
The last thing I'll leave you with is the final version of the whole spec file.
import { Pipe, PipeTransform } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { CoolComponent } from './cool-component';

@Pipe({name: 'translate'})
export class FakeTranslatePipe implements PipeTransform {
  transform(query: string): any {
    return 'Translated!';
  }
}

describe('CoolComponent', () => {
  let pipeSpy: jasmine.Spy;
  let component: CoolComponent;
  let fixture: ComponentFixture<CoolComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        CoolComponent,
        FakeTranslatePipe
      ]
    })
    .compileComponents();
    
    pipeSpy = spyOn(FakeTranslatePipe.prototype, 'transform').and.callThrough();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoolComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should display translated title', () => {
    const debugElements = fixture.debugElement.queryAll(By.css('h1'));
    
    expect(debugElements.length).toBe(1);
    expect(debugElements[0].nativeElement.textContent).toBe('Translated!');
    expect(pipeSpy).toHaveBeenCalledTimes(1);
    expect(pipeSpy).toHaveBeenCalledWith('page-title');
  });
});



*If we know we'll be using the same FakeTranslatePipe in lots of different spec files throughout the project, we could create it in a separate file and import it, but for the purposes of this post we're going to create it in the same file.

Bootstrap Breakpoints

It seems like I'm constantly looking up Bootstrap's breakpoints so I figured I should just put them here for (my own) easy future reference.

XS (Extra Small) SM (Small) MD (Medium) LG (Large) XL (Extra Large) XXL (Extra Extra Large)
V5 <576px 576px ‐ 767px 768px ‐ 991px 992px ‐ 1199px 1199px - 1399px >1399px
V4 <576px 576px ‐ 767px 768px ‐ 991px 992px ‐ 1199px >1199px N/A
V3.3.7 <768px 768px ‐ 991px 992px ‐ 1199px >1199px N/A N/A
CDK <600px 600px - 1024px 1024px - 1439px 1440px - 1919px >1919px N/A

Now that I've put this table together I realize that part of my confusion is that Bootstrap 4 added the XL breakpoint, which caused the scales to shift. Good to know.
Edit: I've added the Angular CDK breakpoints
Edit: I've added the Bootstrap V5 breakpoints

Tuesday, March 13, 2018

Visual Studio Code

I've been using VS Code for a while and I absolutely love it for all of my front-end editing needs. However, there are some shortcuts that I got used to in Visual Studio over the years that are different in VS Code. Fortunately, there's a way to easily rebind shortcuts in VS Code. Listed here are a few of my favorite changes to make to VS Code to get it setup the way I like it.

To change key bindings go to File > Preferences > Keyboard Shortcuts. Once in there you can search for the action and then double-click on it to change the binding. Below is a table with the default VS Code bindings, their corresponding Visual Studio bindings (if applicable), and the action taken. I change all of these before I do anything else in VS Code.

Action VS Code (Default) Visual Studio (Default)
Fold All Ctrl+k, 0 Ctrl+m, Ctrl+o
File: Save All Ctrl+K, S Ctrl+Shift+s 
File: Save As... Ctrl+Shift+s

I found that in recent versions you have to remove the binding for File: Save As... for the new File: Save All binding to work. Just right-click on the existing binding and choose Remove Keybinding in the context menu.
I also like to turn off the little preview pane that is displayed by default on the far right of the main window. To do that, go to View > Appearance > Minimap.

I'll update the table above as I find more shortcuts that don't match (I'm sure there are plenty). As usual, this list is more for me than it is anyone else so if it doesn't help you... make your own.

Monday, December 18, 2017

(My Distaste for) Coding Tests

I've been interviewing for about a month and as part of that process I was recently asked to do Fizzbuzz on a whiteboard and... it did not go well. I was not initially asked to do Fizzbuzz; I was asked how I would make it testable. The conversation went something like this:

Interviewer (I): How would you make Fizzbuzz testable?
Me: All code is inherently testable so I'm not sure I understand your question.
I: The way most people solve Fizzbuzz it is not testable. How would you do it differently?
Me: If the way most people solve Fizzbuz isn't testable then they're solving it wrong because - again - all code is inherently testable.
I: OK. Solve Fizzbuzz on the whiteboard.
Me: I'm not doing Fizzbuzz.
I: *perplexed look on his face* I just want you to show me how you would make Fizzbuzz testable.
Me: OK. *starts writing for loop on whiteboard and stops* I'm not going to write out a solution to Fizzbuzz. You'd basically make it testable by assigning the value ("Fizz", "Buzz", "Fizzbuzz", or the number) to a variable, injecting a logger class, and checking whether that logger class was called with particular parameters.
I: Can you be more specific?
Me: Not really. This isn't a difficult problem so it isn't a difficult solution.

As you can see, the interview got out of hand quickly. Since that day (about two weeks ago) I've been beating myself up for how everything happened and I've come to a few realizations that I want to share.

First and foremost, asking senior software engineers to solve a "problem" like Fizzbuzz is insulting. I have samples of my code freely available on Github and would gladly have written a small application on a computer to satisfy whatever coding requirements they have. Fizzbuzz is a test that should - at best - be given to developers who just finished school to see whether they can actually code.

I'm really conflicted on whether I think they should have just not asked me or I should have just answered. Ultimately, I think it's both. They shouldn't have asked that question, but when they did, I should have answered it. It wouldn't have been difficult to just write out a solution to Fizzbuzz on the whiteboard that was unit testable. I let me ego get the best of me ("You want me to do what?!") and it ended up costing me an opportunity.

Hopefully I've learned from this mistake and I won't react the same way in the future.

Sunday, December 17, 2017

It's Not What You Say, It's What You Say

In November I got the unpleasant news that my office was going to close in 2018. On the plus side, the company gave us almost two full months' notice so we could start getting our resumes up-to-date and looking for work. I've received a couple of offers, but neither of them really felt like the right opportunity for me. One was easy to identify the issues because they were quantifiable (think money, benefits, etc.), but the other was a little trickier.

I went through the full interview process with a medium-sized publicly traded company and I liked almost everything I heard. They used the latest technologies, they had a fun atmosphere, they provided games and drinks and snacks, everybody was really cool, and so on and so on. However, multiple times in the interview they indicated that they are available to work 24/7. The recruiter tried to clarify that they work a pretty standard schedule, but the gut feeling I had remained and I couldn't shake it.

This interview process revealed to me that it's not necessarily what you say, but it's also what you say. What I mean is that during the interview process they told me - I felt in no uncertain terms - that I would need to live and breathe the company if I came on board. That's fine for some people, but that's now what I'm about so it wouldn't have worked for me. Even though they tried to clear it up, even their clarification continued to tell me what I had previously heard.

Ultimately, I might be missing out on a great opportunity, and that would suck. But I'd rather miss out on a company than ignore my gut instinct that says this isn't the right place for me.

Update: I've had a few friends go to work for this company and my suspicions were correct. On top of the 24/7 availability, they have few to no processes (which is a big problem for me). I can confidently say 5 years later that declining this offer was the right move for me.

Tuesday, November 21, 2017

JavaScript Array.Filter

Several times in the recent past I've had a need to grab certain objects from an array based on a value of one of their properties. In Linq in C# I'd do something like this:
filteredItems = allItems.Where(i => i.FirstName == "Mickey");

In TypeScript I don't have Linq functions so I need an alternative when I'm writing Angular. Fortunately, JavaScript includes the Array.prototype.filter function that works very similarly. When I want to do the exact same thing as above, but in JavaScript (and therefore in TypeScripe) I'd do this:
filteredItems = allItems.filter(i => i.FirstName === "Mickey");

Did I say they were similar? Because they're pretty much identical. I'm sure I'll be revisiting this post many times in the future.

Saturday, November 11, 2017

All About Interfaces

I was recently asked for some good reading material on the difference between implementing and injecting interfaces and I couldn't come up with anything. I know the root cause of the lack of material is that the two concepts are totally different, but they are related so it's worth discussing them together.

First let's look at what an interface is in object-oriented programming. The simplest way to think of interfaces is as contracts. If you hire a crew to paint your house you're going to sign a contract with them. You've defined in the contract exactly which parts of the house need to be painted, the color of the paint in each area, and perhaps some small improvements to be done as they paint. When the painter agrees to take on the job, he's agreeing to implement that contract exactly as you specified.

An interface in programming is exactly the same as the contract we had the painter agree to. If we define an interface we're saying that any classes that want to agree to (implement) that interface must be structured exactly as the interface specifies. Let's take our painting example virtual and define our contract as an interface.
   1:  public interface IBindPainters
   2:  {
   3:      List<Improvement> Improvements { get; set; }
   4:  
   5:      Dictionary<Location, Color> Colors { get; set; }
   6:  
   7:      void Improve(Improvement improvement);
   8:  
   9:      void Paint(House house);
   10:  }

Any painter classes we create that want to implement (agree to) this interface (contract) must have a property called Improvements, a property called Colors, and methods called Improve and Paint. The signatures of the methods and types of the properties must also match the interface. So if we create a class called JohnPainter that wants to implement this interface it would at least look like what you see below.
   1:  public class JohnPainter : IBindPainters
   2:  {
   3:      public List<Improvement> Improvements { get; set; }
   4:  
   5:      public Dictionary<Location, Color> Colors { get; set; }
   6:  
   7:      public void Improve(Improvement improvement)
   8:      {
   9:          // do improvements around the house
   10:     }
   11:  
   12:     public void Paint(House house)
   13:     {
   14:         // paint the house
   15:     }
   16:  }

If we create a class called FrankPainter that wants to implement this interface, it would at least look like what you see below.
   1:  public class FrankPainter : IBindPainters
   2:  {
   3:      public List<Improvement> Improvements { get; set; }
   4:  
   5:      public Dictionary<Location, Color> Colors { get; set; }
   6:  
   7:      public void Improve(Improvement improvement)
   8:      {
   9:          // do improvements around the house
   10:     }
   11:  
   12:     public void Paint(House house)
   13:     {
   14:         // paint the house
   15:     }
   16:  }

Both of those classes implement the interface, which means that both John and Frank have agreed to our contract. That's literally all interfaces are for! An interface doesn't specify how the work gets done - Frank and John might each paint that house using completely different processes - and it doesn't actually do anything. It just guarantees that whoever implements the contract agrees to the terms.

So the next question that usually comes up is Why? Why do we use interfaces at all? Well, let's keep moving forward with the house painting example we've been using and see if we can answer that question, too.

As the homeowner, I know how the process of having my house painted is going to work. I'm going to hire a painter, give them the colors to paint each part of the house, show them the improvements that need to be made, have them do the improvements, then paint the house, then I'll pay them. Before I hire the painter, I can define my entire process, like this:
   1:  public class HomeOwner
   2:  {
   3:      private IBindPainters _hiredPainter;
   4:      private House _house;
   5:  
   6:      public HomeOwner(IBindPainters hiredPainter)
   7:      {
   8:          _hiredPainter = hiredPainter;
   9:         _house = new House();
   10:     }
   11:  
   12:     public void HaveHousePainted()
   13:     {
   14:         _hiredPainter.Colors = new Dictionary<Location, Color>();
   15:         _hiredPainter.Improvements = new List<Improvement>();
   16:         foreach (var improvement in _hiredPainter.Improvements)
   17:         {
   18:             _hiredPainter.Improve(improvement);
   19:         }
   20:  
   21:         _hiredPainter.Paint(this._house);
   22:     }
   23:  }

So what does this do for us? Well, we know that whatever painter we hire they're going to have to agree to our contract, so we can setup our entire day before we know who is going to actually paint the house. If we decide to hire Frank we just pass Frank as the painter into our constructor and everything works fine. If we decide to hire John we just pass John as the painter into our constructor and everything works fine.

Since our constructor is expecting an interface (IBindPainters) what it's really expecting is a class that implements that interface. Whether that class is John or Frank makes no difference to how we're going to have our house painter. Whoever we hire is going to have to agree to our contract.

This really comes in handy when we don't know ahead of time which class we'll get. Let's say I'm not the one picking the painter; it's my wife instead, but she can't be home when the painter shows up. She leaves me very clear instructions on what to do when the painter gets there (give him the colors and areas to paint those colors, show him the improvements, have him make the improvements, then have him paint), but she forgets to tell me who she hired. Well, it doesn't matter as long as the person who shows up agrees to the contract.

When the painter shows up - whoever it is - we just plug him into our predefined process and he gets to work. Guess what? That's what injecting an interface means! Injecting an interface just means we provide a class that implements the interface, but we depend on (expect) the interface instead of a specific class.

Let's recap.

  • An interface is just a contract; it cannot be instantiated itself
  • When a class implements an interface, it just means that class agrees to the terms of the contract
  • Injecting an interface means we expect a class that implements an interface to be provided
  • Interfaces do not actually do anything... ever!
Hopefully this helps you out if you've been trying to understand interfaces and/or injecting them.