<?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 Brandon Domingue on Medium]]></title>
        <description><![CDATA[Stories by Brandon Domingue on Medium]]></description>
        <link>https://medium.com/@getsaf?source=rss-65cfe9c32dfd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oqIW08Kp7R3PXBiM</url>
            <title>Stories by Brandon Domingue on Medium</title>
            <link>https://medium.com/@getsaf?source=rss-65cfe9c32dfd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:55:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@getsaf/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[Advanced shallow-render testing for Angular components]]></title>
            <link>https://medium.com/@getsaf/advanced-shallow-render-testing-for-angular-components-452ce74d5f88?source=rss-65cfe9c32dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/452ce74d5f88</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Brandon Domingue]]></dc:creator>
            <pubDate>Fri, 07 Dec 2018 14:33:59 GMT</pubDate>
            <atom:updated>2018-12-07T14:46:00.347Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced shallow-render testing for Angular components — part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RCtrrPUGOx7PQAJRSBf60w.jpeg" /><figcaption>Totally unrelated picture of St. Mary lake. It’s nice though, right?</figcaption></figure><p><em>This is a continuation of </em><a href="https://medium.com/@getsaf/testing-angular-components-with-shallow-render-9334d16dc2e3"><em>Testing Angular Components With shallow-render</em></a></p><p>You already know how to use <a href="https://github.com/getsaf/shallow-render">shallow-render</a> right? In this article, we’ll go over some of the more advanced techniques. I’ll explain along the way how these techniques can help tighten up your test code and eliminate even more boilerplate.</p><h3>Render without the HTML Template</h3><p>In the initial release of shallow-render you could test your components by typing out the same HTML you would in your template. This can be nice to serve as an example of how to use the component in your specs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dabb116704a58a1b6bab1992ce1c0da0/href">https://medium.com/media/dabb116704a58a1b6bab1992ce1c0da0/href</a></iframe><p>You can see that once you need more advanced bindings, we are mimicking the template/controller model in our test by specifying the HTML template to render, along with scope variables in the bind object passed into the renderer.</p><p>This works well, but we could simplify this quite a bit more by eliminating the template and just specifying the bindings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce06571c15e1fa6bf510a558c693a93/href">https://medium.com/media/6ce06571c15e1fa6bf510a558c693a93/href</a></iframe><p>This is my go-to pattern. It allows you to ignore the Angular Template language altogether but we keep type-safety because the bind argument must match types with the component’s inputs.</p><p>You may have noticed that in the second test, we’re not sending in a click handler. When shallow-render renders your component, it inspects the metadata and <strong>automatically spys on event emitters</strong> for you. This means to determine whether events are emitted properly, you can just assert on the emitter to have been called with the correct outputs. This is slightly sleeker than testing with templates and avoids a few scenarios that may make tests easier to read:</p><p>Pros:</p><ul><li>Less code! (no need to specify event bindings)</li><li>Requires binding properties to match names with the component properties which can help avoid confusing a binding name with a component property.</li></ul><p>Cons:</p><ul><li>Sometimes having the HTML in your spec to serve as an example is desirable so other devs can see the usage at-a-glance.</li><li>Does not support rendering projected content or directives.</li></ul><h3>Testing Directives</h3><p>Directives in Angular are very similar to components; so-much so that they are often referred to as the same thing in the Angular codebase. Shallow supports testing directives pretty easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8fb8b30da36b305bb8ebebeaafd1b32/href">https://medium.com/media/a8fb8b30da36b305bb8ebebeaafd1b32/href</a></iframe><p>Note that because directives must be attached to an existing HTML element, you must specify the HTML template to the renderer. Also notice that the element that is returned from the render is the div that the directive was attached to in the HTML.</p><h3>Using Replacement Modules</h3><p>A common pattern in the Angular community is to provide a test module that represents a substitution for a module designed specifically for tests. Angular does this quite often, here’s the <a href="https://angular.io/api/common/http/testing/HttpClientTestingModule">HttpClientTestingModule</a> that is used to substitute the a dummy requestor for HttpClient instances.</p><p>We can use these in our tests by “replacing” the original module with the testing module.</p><p>shallow.replaceModule(HttpClientModule, HttpClientTestingModule)</p><p>Here’s an example of a test using the testing module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e03612b88129f96a1b22366691d4b1/href">https://medium.com/media/d9e03612b88129f96a1b22366691d4b1/href</a></iframe><p>There’s a lot going on here. Much of the complexity here comes from the fact that testing HttpClient requests in Angular is a little verbose. Here are some notes (in the order you will read them from the test).</p><ul><li>We use <a href="https://angular.io/api/core/testing/fakeAsync">fakeAsync</a> and async in our tests. fakeAsync allows us to manually control the flow of promise chains in our component.</li><li>We use shallow’s <a href="https://github.com/getsaf/shallow-render/wiki/Rendering-Class#get">get</a> method to pull injectables from the module. (we also have to cast the HttpTestingController because Angular used an abstract class).</li><li>We setup our HttpClient mocks and then <a href="https://angular.io/api/core/testing/tick">tick</a>. This resolves the request promise chain in the component constructor which in-turn updates the labelText property on the component.</li><li>Since we’ve triggered a UI change, we must detectChanges before we make assertions on the component.</li></ul><blockquote>Note: This is a contrived example intended only to provide some examples of testing with shallow-render. In a real-world application, I would always recommend wrapping calls to HTTP endpoints in a <a href="https://angular.io/tutorial/toh-pt4#why-services">Service Class</a> that encapsulates the HTTP communication. It’ll make your app and testing <strong><em>much easier</em></strong>!</blockquote><h3>Testing with the RouterModule</h3><p>Testing apps that use the Angular Routing module is a hot-topic on the shallow-render issues list. With some of the recent additions in shallow-render it’s pretty straight forward now. Here we find again that Angular has provided us with a testing module for routing (<a href="https://angular.io/api/router/testing/RouterTestingModule">RouterTestingModule</a>). We just need to replace the original RouterModule with the test version and make sure our test module is configured per Angular’s docs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/054fdbbb01f0d820e6daa7f963c94653/href">https://medium.com/media/054fdbbb01f0d820e6daa7f963c94653/href</a></iframe><p>This is the simplest form of testing with routes. You may even supply the RouterTestingModule <a href="https://github.com/getsaf/shallow-render/wiki/Configuration#global-configuration">replacement globally</a> by using alwaysReplaceModule so you don’t have to remember to replace it in each spec.</p><h3>Using ViewChild/ContentChild Selectors</h3><p>Angular allows you to create components that play well together. Sometimes, an outer component may reference a child component using <a href="https://angular.io/api/core/ContentChild">ContentChild</a> selectors. Here’s an example of a list component that automatically activates the first item in the list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8930f650004506c98d72ca5a4ea76622/href">https://medium.com/media/8930f650004506c98d72ca5a4ea76622/href</a></iframe><p>Since shallow will automatically mock out the list-item component in our tests, we need to mock the ListItemComponent&#39;s activate function so we can verify that it is called for the first item in the list. We had to use the HTML Template style of rendering here so we could render children components into our ListContainer component.</p><h4>Side note on isolation in Unit Tests</h4><p>Notice that because this is a test for the ListItemContainer, we don’t really care what the ListItem#activate method does to theListItem because tests for that ListItem behavior should go in the tests for ListItem. Following this model of <strong><em>isolating</em></strong> the component under test will ensure that we are able to refactor the ListItem&#39;s activation behavior without unnecessarily breaking tests for the ListItemContainer. There’s nothing more frustrating than refactoring the internals of one component in a backwards compatible manner and breaking unit tests for some other components that <strong><em>didn’t really break</em></strong>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=452ce74d5f88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why shallow rendering is important in Angular unit tests]]></title>
            <link>https://medium.com/@getsaf/why-shallow-rendering-is-import-in-angular-unit-tests-84569d571b72?source=rss-65cfe9c32dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/84569d571b72</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Brandon Domingue]]></dc:creator>
            <pubDate>Sat, 04 Aug 2018 00:19:25 GMT</pubDate>
            <atom:updated>2020-09-26T17:38:02.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nq_OSzzZ6tF53t9ccLBcCw.jpeg" /></figure><p>If you’re not familiar with <a href="https://github.com/getsaf/shallow-render">shallow-render</a>, check out the <a href="https://medium.com/@getsaf/testing-angular-components-with-shallow-render-9334d16dc2e3">introduction article</a> first.</p><p>This post will dive a little deeper into some basic testing strategies for Angular components in an attempt to explain why we care about shallow rendering in the first place.</p><p>We all know how simple a project starts out. It starts with just a couple of components here and there, then a quick refactor to de-dup some of those components into shared components. Now things are moving quickly, your efforts to create shared components paid off and you are using those shared components across your entire app and writing unit tests along the way, life’s good.</p><p>Now, UX comes back and asks you to change the UI for your most commonly used shared-component, the PersonComponent. There are no changes to the component contract, just some simple CSS and DOM changes and we’re all done. This should be simple right?</p><p>I’ll just make a simple change to the PersonComponent’s HTML so the address is no longer <strong>italic</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPL8G0315nIW-nwGtcRyDA.png" /><figcaption>DOM changes for the PersonComponent</figcaption></figure><p>Quick update to the PersonComponent specs so we’re covered for this change and let’s run the tests for the project…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*cy8dyIT30q6bU_tbA3VdLw.png" /></figure><p>Wait, what? <strong>65 test failures</strong>! I didn’t change how it was used, I just changed how it works on the inside. These tests shouldn’t break?</p><p>After some investigation and some reflection, it looks like the tests for many of the components in your project were written with full-rendering of dependent components. All the ones that used the PersonComponent are broken now. A lot of the assertions that were made were made by inspection of the DOM for the *old* layout of your shared component. It seemed like the right thing to do at first, but now this simple UI change is hard to deal with.</p><p>Let’s look at one of the test failures:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed46d180cc9e3d471dea7ccbbec7c5d4/href">https://medium.com/media/ed46d180cc9e3d471dea7ccbbec7c5d4/href</a></iframe><p>Oh, well there’s the problem. We used the <strong><em>real</em></strong> PersonComponent in the spec for the ArticleComponent and tested that we send the right parameters to the PersonComponent by <strong><em>reaching inside</em></strong> and pulling out labels. Looks like there are 64 other variations of this kind of thing going on in the codebase that I’ll have to change.</p><p>This problem is common and it&#39;s called <a href="https://en.wikipedia.org/wiki/Coupling_(computer_programming)"><em>tight-coupling</em></a>. When we wrote this test, we inadvertently coupled our test to the specific DOM structure of the PersonComponent even though really, the test doesn’t need to know the inner-workings of the PersonComponent to make the assertion it intends to. All the ArticleComponent tests really cared about was that we did render a person, and it was the right one, who cares how it looks or is structured, that’s covered in the tests for the PersonComponent already.</p><p>Writing unit tests is NOT an intuitive task, and is arguably more difficult to master than simply writing feature code. Test tools can help us avoid these issues.</p><p>Here’s the same test written with <a href="https://github.com/getsaf/shallow-render">shallow-render</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c3da1dbc5036a35c5ef05d1d56be61/href">https://medium.com/media/38c3da1dbc5036a35c5ef05d1d56be61/href</a></iframe><p>When using <a href="https://github.com/getsaf/shallow-render">shallow-render</a> we use a mock of the PersonComponent and verify the inputs are set correctly instead of concerning ourselves with the inner details of the rendering. This means we’re focused in on the ArticleComponent in our tests and the other things are out of our way as much as possible. This frees us up to refactor the display of the PersonComponent however we want and the test still passes. Remember that unit tests are here to help us test behavior, not implementation.</p><p>In more complex applications, functional or integration tests can help you cover the full integration of all your components. You’ll typically find that you need far fewer functional tests than units to give you confidence in component interaction but we’ll save this topic for another day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84569d571b72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Angular components with shallow-render — part 1]]></title>
            <link>https://medium.com/@getsaf/testing-angular-components-with-shallow-render-9334d16dc2e3?source=rss-65cfe9c32dfd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9334d16dc2e3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Brandon Domingue]]></dc:creator>
            <pubDate>Fri, 20 Jul 2018 02:33:05 GMT</pubDate>
            <atom:updated>2020-09-26T17:37:16.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkPUFuyhuqPykfxTzwNYkw.jpeg" /></figure><p><em>This article is part-1 of 2. Looking for more advanced stuff, </em><a href="https://medium.com/@getsaf/advanced-shallow-render-testing-for-angular-components-452ce74d5f88"><em>check out part-2</em></a><em>!</em></p><p>I suspect that if you’re reading this article, you’ve been through the trenches of testing components in Angular. If that’s you, I feel your pain. Testing components in Angular is <strong>HARD</strong> but it doesn’t have to be. Good answers for testing Angular components are hard to come by. I’ve talked to other devs about this and I hear a lot of confusion.</p><ul><li>OMG, my TestBed setup is more complicated than the component I’m testing? What am I doing wrong?!</li><li>My component already lives in a module, why do I have to (re)create a module in every spec?</li><li><a href="https://angular.io/guide/testing#no_errors_schema">NO_ERRORS_SCHEMA</a> is designed to prevent error reporting in templates. Don’t I <em>want</em> to know about errors in my tests? Isn’t that the point of writing tests?</li><li>I’m always creating a <a href="https://angular.io/guide/testing#component-inside-a-test-host">test host component</a> in my test and they’re not always easy to work with. Can I avoid this somehow?</li><li>Mocking can get complicated when I use <a href="https://angular.io/guide/testing#component-with-a-dependency">provider stub</a>s. Can I stub over my stub? Is there a better pattern?</li><li>I started writing <a href="https://angular.io/guide/testing#stubbing-unneeded-components">component stubs</a> for testing, they’re not really type-safe Sometimes, using stubs makes my tests pass when they should fail. Now I have hundreds of component stubs and they’re hard to maintain. This is getting out of hand!</li><li>With all these problems… I find that my tests aren’t giving me the confidence I hoped they would. <strong>Is it testing in Angular really worth it</strong>?</li></ul><p>When I started with Angular, I was a bit surprised that these problems hadn’t really been addressed by the community. Let’s solve them.</p><p>Enter <a href="https://github.com/getsaf/shallow-render#shallow-render">shallow-render</a>. The goals are simple:</p><ul><li>Eliminate boilerplate</li><li>Encourage unit-testing best-practices</li><li>ABTS (always be type-safe)</li></ul><p>Let’s dive in. First, here’s an example of a test for a reasonably standard component. It uses some pipes, directives, and other components and a service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be081ff751d6c1356e98446e723331c4/href">https://medium.com/media/be081ff751d6c1356e98446e723331c4/href</a></iframe><p>Whew!!! That was a lot of boilerplate. Here are just some of the issues:</p><ul><li>Our TestBed module looks very similar if not identical to the realNgModule I&#39;ve already added MyComponent to. Total module duplication.</li><li>Since I’ve duplicated my module in my spec, I’m not actually sure the real module was setup correctly.</li><li>I’ve used REAL components and services in my spec which means I have not isolated the component I’m interested in testing.</li><li>This also means I have to follow, and provide all the dependencies of those real components to the TestBed module.</li><li>I had to create a TestHostComponent so I could pass bindings into my actual component.</li><li>My TestBed boilerplate code-length exceeded my actual test code-length.</li></ul><p>Now, let’s look at a shallow-render version of the same tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae2c14b2d28ce7819b9c68febec3b33e/href">https://medium.com/media/ae2c14b2d28ce7819b9c68febec3b33e/href</a></iframe><p>Here’s the difference:</p><ul><li>Reuses (and verifies) MyModule contains your component and all its dependencies.</li><li>All components inside MyModule are automatically mocked identical inputs/outputs. This is what makes the rendering &quot;shallow&quot;.</li><li>The tests have far less boilerplate which makes the tests easier to follow.</li><li>In the first test, we decided to use HTML to render the test-component IN THE SPEC where it’s easy to find. Each spec may have different templates, no problem.</li><li>In the second test, we chose not to use HTML, we just went straight for the bindings. The bindings here are type-safe and the output property’s emit function was automatically spied on.</li></ul><p>So, how do we do this? First let’s look at the test setup. It’s simply:</p><p>new Shallow(MyComponent, MyModule)</p><p>Now, what happens behind the scenes is that we collect your test setup options but we <em>do not render just yet</em>, this is just the setup. Then, in the test we have:</p><p>shallow.render(&#39;&lt;my-component linkText=&quot;my text&quot;&gt;&lt;/my-component&gt;)</p><p>At this point, we take all the setup that’s been collected up to this point and collapse it all into a TestBed test module behind-the scenes. This gets a little complicated, but it basically boils down to:</p><ul><li>Setup a test module by mocking everything inMyModule *except* for MyComponent because that’s what we’re testing.</li><li>Create a test-host component and inject the template HTML from the render command.</li><li>Render the component, detect changes, and hand it back to the test.</li></ul><p>Obviously, that’s just for a simple test case. Things can get pretty complicated in Angular so let’s zoom in on a particularly troublesome section of testing, .</p><h3>Mocks</h3><p>Sometimes, we need to mock a service. Angular suggests using <a href="https://angular.io/guide/testing#provide-service-test-doubles">test doubles</a> but with shallow-render, mocking is built-in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3f065a0975ed4cdff0c9e0383839ff4/href">https://medium.com/media/f3f065a0975ed4cdff0c9e0383839ff4/href</a></iframe><p>The first argument to the mock method is the thing you wish to mock, the second argument is a Partial&lt;ThingToMock&gt; so your mock properties and methods are type-safe. Also, any methods you place on your mock will be spy’d on automatically in case you need to make assertions on them.</p><p>It’s also common practice to setup your mocks so that all the tests in the file use the same mock(s). That’s a pretty easy tweak, just move that mock to the beforeEach block and you’re done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fe9bc28a814d6fedeb3a97b947e434d/href">https://medium.com/media/1fe9bc28a814d6fedeb3a97b947e434d/href</a></iframe><p>If a few of your tests needs to override the default mocks, that’s ok, just mock it again and the last-mock-wins.</p><p>If you’re paying close attention here, you’ll notice that calls to mock are chain-able. You can mock as many things as you like in the chain, then just call render() at the end. You may also mock multiple methods/properties on a class with a single call to mock().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe03d25d996a48d61edf54edfe8880b4/href">https://medium.com/media/fe03d25d996a48d61edf54edfe8880b4/href</a></iframe><p>There’s a pretty basic 101 course but If you would like to learn more:</p><ul><li>The code is on github: <a href="https://github.com/getsaf/shallow-render">shallow-render</a></li><li>Lots of <a href="https://getsaf.github.io/shallow-render">documentation</a>!</li><li>There are LOTS of examples in the official <a href="https://stackblitz.com/github/getsaf/shallow-render-stackblitz">StackBlitz project</a>. These examples also serve as part of the test coverage for the library itself.</li></ul><p>I‘m pretty passionate about this stuff so if you have any questions, drop a message in the issues section on the github project.</p><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9334d16dc2e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>