A Simple Mock Component for Angular 2

I’ve been writing a lot of Angular 2 lately (and really liking it). The testing experience is particularly nice, but I was surprised to learn there isn’t a built-in way to mock out or ignore whole components.

For example, say you’d written a PersonComponent, and in constructing that component, you’d created some nice subcomponents, like a head, arms, legs and so forth:

And let’s say you wanted to write some tests for PersonComponent. If your head, torso, arm and leg subcomponents were super-simple, containing only markup and CSS maybe, the test would be easy: just instantiate your PersonComponent using the excellent TestBed, write some expectations, and get on with your day.

But it’s often the case that those subcomponents aren’t simple at all — they might have dependencies of their own that need to be injected, lifecycle hooks to be handled, etc. It’s not uncommon to be greeted, when you run your PersonComponent test, with a sound rejection from Angular that CraniumComponent happens to depend on IQService— and you have failed, dear developer, to address this dependency in setting up your test.

What should you do? You could certainly mock out theIQService to make the error go away. But should you? After all, PersonComponent doesn’t need IQService (that’s a CraniumComponent thing), and you’ll probably have mocked out IQService already (because you’re awesome) in the tests for CraniumComponent.

Instead, what you should do is tell Angular that for purposes of testing yourPersonComponent, you couldn’t care less about what CraniumComponent needs — you just want to make sure PersonComponent includes a CraniumComponent. If it does, you’re happy.

Surprisingly, though, there isn’t a built-in way to tell Angular to ignore the CraniumComponent component entirely. So I wrote one! It’s very simple, actually:

All it really does is export a function that returns a Component instance of an empty class; you supply it with the same set of properties you would any other component, then use it in a module declaration with the selector you want to mock out:

And that’s all there is to it. Enjoy!


Update: I’ve gone ahead and packaged this as a module on NPM:

npm install --save-dev ng2-mock-component

Source is on GitHub. Feedback and contributions are welcome!

Like what you read? Give Christian Nunciato a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.