Monthly Archives: بهمن 1394

11 Free UX e-Books Worth Reading for 2016

Aside from cat videos, the greatest gift the internet gives us is knowledge.

But how can you separate the genuine career boosters from just another book on your to-read pile? Below, we’ve listed out the 11 best free UX design books to check out as we enter the new year.

Web UI Design for the Human Eye

Web UI Design for the Human Eye – UXPin

UXPin explains the craft of UI and UX design through the science of human sight.

Any designer in a visual medium can benefit from knowing the basics, and the two-volume series Web UI Design for the Human Eye teaches them in an easy-to-understand way that relates to web design.

Volume 1 discusses the emotional effects of different colors, influencing user sight flows, and applying the Gestalt principles that govern optical illusions. Volume 2 goes into further detail by explaining common sight behaviors, the F-pattern and the Z-pattern, typography, and overall layout organization.

Pixel Perfect Precision

Pixel Perfect Precision Handbook 3 – ustwo

Regularly updated over the last four years, the third and latest version of the Pixel Perfect Precision Handbook brings updated content to a classic go-to manual for visuals in web design.

This e-book gains its fans with its focus on visual design and includes how-to instructions for Photoshop. The new update features 40 new pages of content.

UX Storytellers

UX Storytellers: Connecting the Dots

A true classic of UX design e-books, UX Storytellers remains relevant thanks to its unique structure: it’s not a how-to guide, but a collection of self-sufficient stories and tips from 42 actual UX experts.

With 586 pages, you can pick up this book anywhere and anytime to learn something new, and it comes in handy when you need a fresh perspective.

UI Design 2015-2016

UX Design 2015 & 2016 -Successful Trends for Digital Products

Looking back at the trends from 2015, this book analyzes what worked, why, and how to implement it going forward.

UX Design Trends 2015 & 2016 explores the 6 most successful UX trends at the moment and outlines the best practices for each, including case studies of popular sites like Waze, Spotify, Vine, Virgin America, and many more.

Topics like personalization, micro-interactions, and multi-device experiences will only become more important with time.

The Magic of CSS

Magic of CSS – Adam Schwartz

Love it or hate it, CSS now plays a big role in modern web design. Adam Schwartz’s The Magic of CSS dissects the language in simple, easy-to-follow guidelines, and shows example code and diagrams. The more technical and complicated areas even have templates and data reference charts.

The book is available in its entirety online, so if you ever find yourself wondering about a specific aspect, no matter how small the answer is only a few clicks away.

The UX Reader

The UX Reader – MailChimp UX

MailChimp’s The UX Reader covers the discipline of UX design from front to back. This all-inclusive guide is great for beginners starting from scratch but is also a handy reference guide for experts to keep on their digital shelves.

This e-book lays out UX design into the five categories of Collaboration, Research, Design, Development, and Refinement. Each category is further divided into article-like sections written by different members of the MailChimp UX staff, so you can pick and choose the topics relevant to you.

50 User Experience Best Practices

50 User Experience Best Practices Above the Fold

A classic in UX e-books, the seminal 50 User Experience Best Practices was so successful, it actually outlasted the UX design agency that wrote it.

This e-book lists out 50 tips to improve your user experience across the board, spanning the fields of user research, process flow, content strategy, planning, and front-end development. With specific advice on a wide-range of topics, there’s something for everyone. The casual tone and memorable graphics certainly don’t hurt either.

Web UI Design Best Practices

Web UI Design Best Practices – UXPin

Web UI Design Best Practices is UXPin’s version of a cover-all guide. As with their other e-books, this one offers the same technical analysis explained through simple language that regular readers have come to expect.

This e-book is broken up into sections on navigation, color, typography, UI patterns, and visual hierarchy. The benefit of this book is how it combines other disciplines of web design, namely interface and graphic design. UX design, in general, is an abstract field, and is never separated from the other components of web design.

Learn From Great Design

Learn from Great Design . Vol 1 – Tom Kenny

Tom Kenny runs the blog Inspect Element, which deconstructs a new sight every week and explains what they do well. Kenny goes through page by page, across different devices like desktop and mobile, and illustrates his points with multiple screenshots.

While a fuller book is available for purchase, the free downloadable content, Learn from Great Design, collects three such case studies and cycles them periodically.

This teaching strategy is quite effective, especially in a visual medium like web design. The comparison of sites across devices is invaluable for maintaining a consistent UX, and this detailed treatment simply isn’t offered by most free e-books.

Bright Ideas User Experience Designers

Bright Ideas for User Experience Designers – Userfocus

Another classic, Bright Ideas for User Experience Designers looks at the practice of UX design from the eyes of the UX experts at Userfocus. The best part about this e-book is its humor and laid-back tone, both of which contribute to its memorability.

With fun acronyms like "the CRAP way to usability" and analogies involving the Beatles, this book is as entertaining as it is educational.

Userfocus offers a series of free UX e-books targeting different career paths. If this book seems helpful, check out the other "Bright Ideas for…" books aimed at either UX managers or UX researchers.

Web Design Trends

Web Design Book of Trends 2015 & 2016 – UXPin

Last on our list is UXPin’s Web Design Book of Trends 2015-2016, one of their latest.

The web design industry advances rapidly, keeping up with technological advances, the trends of user preferences, and simply discovering new best practices in a field that is still, relatively, young. The same techniques that were cutting-edge last year can make your product seem outdated this year.

UXPin’s book keeps designers up-to-date. This volume covers the theory and best practices of trends like hero images, card layouts, long-scrolling, and HD visuals, drawing on examples from 166 popular sites like Apple, Dropbox, and Spotify, and featuring 100 additional online resources.

Why We Support Teammates with Dependents (and Why it’s No Longer Part of our Salary Formula)


Why We Support Teammates with Dependents (and Why it’s No Longer Part of our Salary Formula)

One of the things we’ve always been interested in doing at Buffer is looking at compensation differently and transparently.

In the latest update of our transparent salaries formula, one key change was that we began to pay teammates more money if they had dependents, or family members who depended on their income.

The formula that we originally came up with offers an extra $3,000 a year for every family member that immediately relies on your income. This can be quite broad — for example, a spouse or partner going through school or out of work, or a grandparent to whom you’re sending money to help with expenses. We trust each teammate to make the decision that feels best for them, no questions asked.

Buffer’s dependents policy

  • $3,000 per dependent who depends on your salary
  • Can be for spouses, partners, children, grandparents, aunts or uncles, etc.
  • Can have as many additional family members as you need

Along with The Good Life Curve, this was one of the elements that got the most questions and comments when we shared the new formula recently.

I wanted to take the time to explain why we originally made it an option for team members to factor into their salaries those who depend on their income — and why we now have a different path, after hearing great insights from many of you.

Why include dependents and family?

Why bring family or dependents into the equation at all?

One of the things both Joel and I experienced growing up in Europe is the idea of supporting families from a government perspective. In Austria, my family got $2,000 in support per year per child, and a similar program exists in the UK for certain levels of income.

We have always felt that was a good thing to do, and as Buffer’s cofounders we now have the opportunity to show support for our team in a similar way.

Raising children, and other familial responsibilities, costs a lot of money. We have an opinion that it’s something we should show support for.

It’s our intuition that $3,000 isn’t quite enough money to incentivize anyone to have children, and that’s not the goal of this stipend. Rather, we want to help our teammates feel taken care of if they happen to have children or others in their family who rely on their income.

This is a partially a selfish, self-serving attempt to take some challenges away from people so they carry fewer worries about money around when they work on Buffer (or do everything else).

We know there are a lot of other circumstances people can be in that might also require support — for instance, student loans, or a mortgage on your house — and we don’t want to dismiss any of those.

In the long term of evolving Buffer’s culture and values, I expect us to tackle many more of the kinds of issues that are a burden for team members.

To start, we picked one dependents because it felt like a common, applicable, useful starting point.

Listening to your feedback: We removed this element from salary

It’s been incredible how many amazing, thoughtful comments and discussion points were raised around this. We’ve been listening to all of them!

After all the conversations we’ve had, we continue to feel it’s the right thing to do to support teammates with these fairly small grants.

But we got a lot of helpful feedback that having this money folded into a person’s overall compensation felt off, as if we were valuing people with family obligations in a different way than other teammates.

Here’s a sampling:

@joelgascoigne @buffer what has family got to do with salary? Does it make me a better employee if I have kids? What if I can’t have them?
— Chris C (@chris_campbell) November 24, 2015
i can’t decide, whether i agree with @buffer‘s decision to pay people, who have family more / people who are single less. hm. — Kathrin Folkendt (@kathaka) November 24, 2015
@joelgascoigne @buffer why do you get more for having a family? Kinda discriminates against single people.
— Andy P (@andypngr) November 25, 2015

We hear you, and we completely agree.

It doesn’t make sense to pay someone more because of their family circumstances. Especially when it comes to equity — in our existing formula, people with kids or others who depend on their salaries would have gotten more equity, which wouldn’t feel quite right at all.

Therefore, we’ve moved the family element out of the salary formula entirely. It’s no longer part of our formula on our working spreadsheet or represented in our salary calculator.

Instead, we’re adding a new dependents grant into our benefits. We already have a number of perks and benefits that Buffer provides and pays for, and the dependents grant feels like it has a much more reasonable place there.

We’re still developing a process around it, but this will be a yearly grant that any teammate can apply for by sharing their particular family circumstances. (Teammates who were previously receiving this money through the salary formula have already been grandfathered in for this year).

The formula before this change:

(overall base + location base + cost of living)* role value * experience + risk + dependents = salary

The formula after this change:

(overall base + location base + cost of living)* role value * experience + risk = salary

Here’s an example, putting all this together:

An advanced engineer, living in Cape Town, who chooses more equity and has 2 kids and a husband depending on her income, would previously have made this:

  • $60,662 x 1.20 + $9,000 + $0 = $81,794

Now this same teammate makes:

  • $60,662 x 1.20 +$0 = $72,794

However, she can apply for a dependents grant of up to $9,000 to help support those who are depending on her salary.

We feel we’re painting a clearer picture with this change, and we’d love to hear how it feels to you.

Is this fair?

A question that we feel might remain as we continue to support teammates with these fairly small grants is this one: Is this fair?

We’ve thought about this question a lot, and we’ve come to the conclusion that fair does not always mean equal.

We could pay everyone the exact same wage (something we’ve actually considered in the past!) but we’re not the exact same people. We have different locations, preferences, and life situations. And we believe that those differences should have the opportunity to be reflected in our compensation.

On the whole, Buffer’s goal is to be as generous as possible and take money out of the picture as a concern for any teammate. So for those who face an extra burden from a monetary perspective, we want to be there to support them.

We want to look at compensation with wholeness, empathy and compassion.

This image helps me understand this concept the best:

Dependents is perhaps the first example of our move in this direction, and I have an intuition these changes won’t always feel fair to everyone.

In the future, we’re likely to add more of these elements, like:

  • An additional allowance for our “digital nomad” teammates, who incur extra costs by traveling around the world. We want to support people in finding the place where they feel happiest.
  • A correction for exchange rates and taxes, which vary greatly by country. (We know, for example, that Buffer team members in France pay a lot of extra taxes that others don’t.)

I know we’ll learn a lot from these experiences.

I’m so grateful for the many people who voiced their opinion on this topic and helped us make what we believe is a better decision here.

This experience has reminded me that being transparent has the amazing benefit of helping you hear from a lot of incredibly smart people. Without them, we wouldn’t have been able to come to this conclusion.

I know our formula remains far from perfect, and it’s invaluable to hear from all of you about how we can make it better for the future.

If you’d be up for it, I’d love to hear your thoughts about this change, how it feels, and what it might be missing. I’m listening!

P.S. Get all our posts on workplace culture, productivity, transparency and more in your email. Sign up now.


Originally published at open.buffer.com on January 14, 2016.

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Why We Support Teammates with Dependents (and Why it’s No Longer Part of our Salary Formula)


Why We Support Teammates with Dependents (and Why it’s No Longer Part of our Salary Formula)

One of the things we’ve always been interested in doing at Buffer is looking at compensation differently and transparently.

In the latest update of our transparent salaries formula, one key change was that we began to pay teammates more money if they had dependents, or family members who depended on their income.

The formula that we originally came up with offers an extra $3,000 a year for every family member that immediately relies on your income. This can be quite broad — for example, a spouse or partner going through school or out of work, or a grandparent to whom you’re sending money to help with expenses. We trust each teammate to make the decision that feels best for them, no questions asked.

Buffer’s dependents policy

  • $3,000 per dependent who depends on your salary
  • Can be for spouses, partners, children, grandparents, aunts or uncles, etc.
  • Can have as many additional family members as you need

Along with The Good Life Curve, this was one of the elements that got the most questions and comments when we shared the new formula recently.

I wanted to take the time to explain why we originally made it an option for team members to factor into their salaries those who depend on their income — and why we now have a different path, after hearing great insights from many of you.

Why include dependents and family?

Why bring family or dependents into the equation at all?

One of the things both Joel and I experienced growing up in Europe is the idea of supporting families from a government perspective. In Austria, my family got $2,000 in support per year per child, and a similar program exists in the UK for certain levels of income.

We have always felt that was a good thing to do, and as Buffer’s cofounders we now have the opportunity to show support for our team in a similar way.

Raising children, and other familial responsibilities, costs a lot of money. We have an opinion that it’s something we should show support for.

It’s our intuition that $3,000 isn’t quite enough money to incentivize anyone to have children, and that’s not the goal of this stipend. Rather, we want to help our teammates feel taken care of if they happen to have children or others in their family who rely on their income.

This is a partially a selfish, self-serving attempt to take some challenges away from people so they carry fewer worries about money around when they work on Buffer (or do everything else).

We know there are a lot of other circumstances people can be in that might also require support — for instance, student loans, or a mortgage on your house — and we don’t want to dismiss any of those.

In the long term of evolving Buffer’s culture and values, I expect us to tackle many more of the kinds of issues that are a burden for team members.

To start, we picked one dependents because it felt like a common, applicable, useful starting point.

Listening to your feedback: We removed this element from salary

It’s been incredible how many amazing, thoughtful comments and discussion points were raised around this. We’ve been listening to all of them!

After all the conversations we’ve had, we continue to feel it’s the right thing to do to support teammates with these fairly small grants.

But we got a lot of helpful feedback that having this money folded into a person’s overall compensation felt off, as if we were valuing people with family obligations in a different way than other teammates.

Here’s a sampling:

@joelgascoigne @buffer what has family got to do with salary? Does it make me a better employee if I have kids? What if I can’t have them?
— Chris C (@chris_campbell) November 24, 2015
i can’t decide, whether i agree with @buffer‘s decision to pay people, who have family more / people who are single less. hm. — Kathrin Folkendt (@kathaka) November 24, 2015
@joelgascoigne @buffer why do you get more for having a family? Kinda discriminates against single people.
— Andy P (@andypngr) November 25, 2015

We hear you, and we completely agree.

It doesn’t make sense to pay someone more because of their family circumstances. Especially when it comes to equity — in our existing formula, people with kids or others who depend on their salaries would have gotten more equity, which wouldn’t feel quite right at all.

Therefore, we’ve moved the family element out of the salary formula entirely. It’s no longer part of our formula on our working spreadsheet or represented in our salary calculator.

Instead, we’re adding a new dependents grant into our benefits. We already have a number of perks and benefits that Buffer provides and pays for, and the dependents grant feels like it has a much more reasonable place there.

We’re still developing a process around it, but this will be a yearly grant that any teammate can apply for by sharing their particular family circumstances. (Teammates who were previously receiving this money through the salary formula have already been grandfathered in for this year).

The formula before this change:

(overall base + location base + cost of living)* role value * experience + risk + dependents = salary

The formula after this change:

(overall base + location base + cost of living)* role value * experience + risk = salary

Here’s an example, putting all this together:

An advanced engineer, living in Cape Town, who chooses more equity and has 2 kids and a husband depending on her income, would previously have made this:

  • $60,662 x 1.20 + $9,000 + $0 = $81,794

Now this same teammate makes:

  • $60,662 x 1.20 +$0 = $72,794

However, she can apply for a dependents grant of up to $9,000 to help support those who are depending on her salary.

We feel we’re painting a clearer picture with this change, and we’d love to hear how it feels to you.

Is this fair?

A question that we feel might remain as we continue to support teammates with these fairly small grants is this one: Is this fair?

We’ve thought about this question a lot, and we’ve come to the conclusion that fair does not always mean equal.

We could pay everyone the exact same wage (something we’ve actually considered in the past!) but we’re not the exact same people. We have different locations, preferences, and life situations. And we believe that those differences should have the opportunity to be reflected in our compensation.

On the whole, Buffer’s goal is to be as generous as possible and take money out of the picture as a concern for any teammate. So for those who face an extra burden from a monetary perspective, we want to be there to support them.

We want to look at compensation with wholeness, empathy and compassion.

This image helps me understand this concept the best:

Dependents is perhaps the first example of our move in this direction, and I have an intuition these changes won’t always feel fair to everyone.

In the future, we’re likely to add more of these elements, like:

  • An additional allowance for our “digital nomad” teammates, who incur extra costs by traveling around the world. We want to support people in finding the place where they feel happiest.
  • A correction for exchange rates and taxes, which vary greatly by country. (We know, for example, that Buffer team members in France pay a lot of extra taxes that others don’t.)

I know we’ll learn a lot from these experiences.

I’m so grateful for the many people who voiced their opinion on this topic and helped us make what we believe is a better decision here.

This experience has reminded me that being transparent has the amazing benefit of helping you hear from a lot of incredibly smart people. Without them, we wouldn’t have been able to come to this conclusion.

I know our formula remains far from perfect, and it’s invaluable to hear from all of you about how we can make it better for the future.

If you’d be up for it, I’d love to hear your thoughts about this change, how it feels, and what it might be missing. I’m listening!

P.S. Get all our posts on workplace culture, productivity, transparency and more in your email. Sign up now.


Originally published at open.buffer.com on January 14, 2016.

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Uber haunted by the ghost of Flash: your app doesn’t need an intro


Uber haunted by the ghost of Flash: your app doesn’t need an intro

Are you old enough to remember the bad old days of 2000–2004, when web designers everywhere learned some totally awesome Flash and couldn’t wait to deploy it on every project?

The reason for using Flash was simple: it was suddenly available nearly everywhere, and it could do things that plain old HTML+JavaScript in Microsoft’s stale browser could only dream of.

Macromedia, the company behind Flash (eventually acquired by Adobe), had been exceptionally adept at negotiating preload agreements for the Flash Player and its web browser plugin. By December 2001, Flash 4 was available on about 94% of desktop computers worldwide. This was an astonishing reach for a software runtime — it rivalled even Microsoft Windows.

The secret to Flash’s wide reach was that the companies preinstalling it didn’t perceive it as a software runtime. It was just a harmless little tool for lightweight web-optimized vector animation… Although one that happened to include a complete JavaScript-compatible programming language. (By 2007, the cat was out of the bag: Adobe was turning Flash into a real platform, and the competitors who had been haplessly preloading Flash had woken up. Apple refused to include Adobe’s runtime into iOS even though it broke much of the web at the time. But I digress…)

When Flash was suddenly available everywhere, designers saw their chance to make the web “come alive” and jumped on it. Instead of boring Verdana type and web-safe colors, you could now have full-screen animated content!

Of course, the problem was that most websites were simply displaying information and forms (just as today), so they didn’t actually need full-screen animated content anywhere. Hence the invention of the Flash intro. For 5–30 seconds, the user would watch something like a poorly produced TV commercial before entering the site. Although this was pitched to the client as “powerful branding”, it was really more about the web designer desperately wanting to use Flash somewhere. (I know — I did a few of those projects too back then. Guilty!)

It all seems silly now… But the ghost of the intro has never really left us. It’s been lurking all this time in mobile apps, which often feature a “splash screen” that displays the app’s logo and perhaps a fancy progress bar.

Never mind that Apple’s Human Interface Guidelines strongly recommend avoiding splash screens and instead jumping directly to the app’s content. These days clients actually demand splash screens because they’ve seen them on all the big-name apps and assume it’s a necessity.

When a company rebrands, the temptation to spend just a little more time showing the awesome new logo can be overwhelming. That’s what has happened to Uber. You can read about their totally amazing new design in The Verge’s article Uber’s app takes longer to open thanks to its new logo.

Here it is, courtesy of Ben Cunningham on Twitter… And if you’re an Uber user, be prepared to see this zoom-and-bounce-and-zoom-and-bounce sequence often. (It’s 7 seconds long but feels longer when you’re holding a phone.)

The rebirth of the Flash intro in 2016’s mobile apps is partly due to new tools. As Flash was the pretty face that unleashed a thousand ugly intros, beautiful new mobile-oriented prototyping tools such as Principle have a strong focus on animation.

The downside of having great new tools is that designers don’t yet know what to do with them. Just like websites in 2001, most mobile apps really don’t need that much animation. But when animation tools is all you have, everything looks like it could be bouncing and swooping just a little bit more.

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Dead Men Write No Code


Dead Men Write No Code

I am a hypochondriac. In the back of my head I rationalize this as an evolutionary advantage. And in fact, it may have just saved my life.

I work long hours, in a chair, writing code (and of course this article applies to anyone who sits a lot). The sole reason I am writing this is to warn you of the danger you might be in if you are anything like me.

A couple of weeks ago, I got a pain in my lower left leg which almost felt like a sprain, but I knew I had not sprained it. It let it persist for about two weeks figuring that it would go away, but it did not. So, late at night I did what any hypochondriac does, I Googled it.

The first thing that came up was “Deep Vein Thrombosis” or DVT. From that article:

“ Blood clots (deep vein thrombosis DVT and pulmonary embolism PE) affect upwards of 600,000 Americans each year and cause more deaths each year than the more well-publicized occurrences of breast cancer, AIDS, and motor vehicle accidents, yet they are virtually unheard of.”

A DVT is a blood clot in a deep vein (your main circulatory system). The danger is that it can break free and flow to your lungs or heart, and will cause a pulmonary embolism (PE). How do you know if you are experiencing a PE? Well, one of the likely symptoms is that you will be dead.

I called in to my health care provider’s on-call nurse, and I was expecting the usual “probably nothing to worry about, schedule an appointment if it persists.” However, the nurse advised that I have someone drive me to the ER immediately.

The nurse had me coming to the ER based on a protocol that meant my life was potentially in danger, so that made me nervous. I had my blood drawn, x-rays taken, and then an ultrasound. The ultrasound detected some irregularities. It turned out that I had a clot in my system, but not in a deep vein. Such a clot is better than having a DVT, but that clot could have appeared anywhere (or migrated from a DVT), and it can still turn into a DVT or PE if not monitored and tended to. This was a warning shot that happened to hit my leg instead my head or chest. In the doctor’s own words, he told me I could “just as easily be dead right now.” I was lucky, but you might not even get a warning shot. The symptoms are not always clear, or even present for very long. Even if you survive a PE, it will adversely affect you the rest of your life.

The simple truth is that if you are getting blood clots in your 30s (I am 34), there is something horribly wrong with your lifestyle* and you are on the fast track to death, be it from cardiovascular disease or otherwise. Needless to say, this was a wake-up call for me. I had been blind-sided by my own work ethic, and frankly, selfish. Am I ready to leave my wife without a husband or my daughter without a father?

If you think you are not at risk for this because you are young and relatively healthy, let me break some news to you: I am young and “relatively healthy.” Let me explain what I mean by “relatively healthy” — my blood pressure is usually around 110/70, I walk at least 1–3 miles per day (sometimes more), I do push-ups and pull-ups very often (sometimes daily), my blood work checks out as completely normal in every respect (including low cholesterol), and prior to this my checkups revealed nothing abnormal.

However, you can’t go strictly by the numbers. What those numbers don’t reveal is that for the past 5 years I’ve spent the vast majority of it sitting, and very, very little of it with a significantly elevated heart rate.

I am overweight, but not extremely so — I weigh a bit over 200 and my ideal weight is more around 180. If you will forgive the douchey picture, this is me just 6 years ago, weighing 178:

Yes, its a little embarrassing to post this, but I really want to drive home the fact that even letting your health slip over a relatively short time can be dangerous (additional notes on my past exercise history at bottom). Looking at me, you wouldn’t likely tag me as someone who could die early (even at my current state at 20 pounds heavier). If this can happen to me, why not to you? If you think you are simply too young to get a DVT, I have seen cases occur to people in their early 20s.

I neglected my health for several years and I knew something bad was happening to my body. I would sit for up to 12 hours per day working, with small breaks here and there (mostly chores and walking my dogs). I’ve worked 80-hour weeks for the past decade (occasionally 100-hour weeks), but the past 5 years I have been particularly immobile. I have rationalized it with the “wealth before health” attitude that seems to be prevalent in the startup world (even though wealth is not my primary motivator, you get the idea). “I just need to make it through this year, and then I can exercise” and “exercise will kill my productivity” are two lies I have been telling myself for the past several years. I have taken a similar attitude with my diet, which is far from great.

Right now, if you are in my situation, seriously reconsider your life before its no longer an option. Nobody owns your life, and to those who think they do: you are more valuable to them as a healthy person than as a liability. Beyond that, I won’t go into giving you specific advice for being healthy, other than recommending sitting less (if that means getting a standing desk, that is one option)**.

Talk is cheap, and what good are my words if I can’t set an example? Starting tomorrow, I am drastically changing my diet and doing real cardio every day (i.e. running, not walking). I am not sitting until my feet hurt (I even wrote this article standing up). Even if it is embarrassing, I am having everyone hold me accountable and I am reporting my weight to social media every day (I’ll spare you the half-naked photos though until I am healthy again).

Additional Notes:

* As others have since pointed out, there are many potential causes of DTVs and clots, and while your health does play a large role, other things may effect people even in good health — flying and birth control are two common catalysts. I did fly one week prior to my first symptoms, so that was likely a contributing factor. However, I have taken many long flights without a resulting clot, and I think either way I would be less likely to have gotten a clot had I been healthier leading up to this. Even ignoring clots, it is generally good health advice to not sit for too long, exercise, and eat well.

** This is not just to fight off blood clots — sitting for too long is shown to have many adverse health effects, including negating the positive effects of exercise. Standing all day is also shown to be bad for you (if the studies are to be believed).

I am not nor do I claim to be an expert on any of these matters. I could easily be wrong about any given subject. As with anything, take the time to do your own additional research! :)

Notes on my past exercise habits since someone asked (I am omitting many other things I did like swimming, weight lifting, gymnastics, etc):

  • 1981–2000 (relatively active growing up, grew up in the outdoors, but never played sports outside of school)
  • 2000–2004 (ran 2–3 miles every single day, about 7 minutes per mile)
  • 2004–2006 (ran 1 to 2 times per week, same pace)
  • 2006–2008 (ran every day, about 2 miles, same pace)
  • 2008–2009 (did not run much but did a lot of other types of exercise, not much cardio)
  • 2009–2010 (ran 100+ flights of stairs per day, + 1–2 miles)
  • 2011 to present (cardio has gradually decreased to a point where I very rarely run, but I walk my dogs every single day 1–3 miles).

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Uber haunted by the ghost of Flash: your app doesn’t need an intro


Uber haunted by the ghost of Flash: your app doesn’t need an intro

Are you old enough to remember the bad old days of 2000–2004, when web designers everywhere learned some totally awesome Flash and couldn’t wait to deploy it on every project?

The reason for using Flash was simple: it was suddenly available nearly everywhere, and it could do things that plain old HTML+JavaScript in Microsoft’s stale browser could only dream of.

Macromedia, the company behind Flash (eventually acquired by Adobe), had been exceptionally adept at negotiating preload agreements for the Flash Player and its web browser plugin. By December 2001, Flash 4 was available on about 94% of desktop computers worldwide. This was an astonishing reach for a software runtime — it rivalled even Microsoft Windows.

The secret to Flash’s wide reach was that the companies preinstalling it didn’t perceive it as a software runtime. It was just a harmless little tool for lightweight web-optimized vector animation… Although one that happened to include a complete JavaScript-compatible programming language. (By 2007, the cat was out of the bag: Adobe was turning Flash into a real platform, and the competitors who had been haplessly preloading Flash had woken up. Apple refused to include Adobe’s runtime into iOS even though it broke much of the web at the time. But I digress…)

When Flash was suddenly available everywhere, designers saw their chance to make the web “come alive” and jumped on it. Instead of boring Verdana type and web-safe colors, you could now have full-screen animated content!

Of course, the problem was that most websites were simply displaying information and forms (just as today), so they didn’t actually need full-screen animated content anywhere. Hence the invention of the Flash intro. For 5–30 seconds, the user would watch something like a poorly produced TV commercial before entering the site. Although this was pitched to the client as “powerful branding”, it was really more about the web designer desperately wanting to use Flash somewhere. (I know — I did a few of those projects too back then. Guilty!)

It all seems silly now… But the ghost of the intro has never really left us. It’s been lurking all this time in mobile apps, which often feature a “splash screen” that displays the app’s logo and perhaps a fancy progress bar.

Never mind that Apple’s Human Interface Guidelines strongly recommend avoiding splash screens and instead jumping directly to the app’s content. These days clients actually demand splash screens because they’ve seen them on all the big-name apps and assume it’s a necessity.

When a company rebrands, the temptation to spend just a little more time showing the awesome new logo can be overwhelming. That’s what has happened to Uber. You can read about their totally amazing new design in The Verge’s article Uber’s app takes longer to open thanks to its new logo.

Here it is, courtesy of Ben Cunningham on Twitter… And if you’re an Uber user, be prepared to see this zoom-and-bounce-and-zoom-and-bounce sequence often. (It’s 7 seconds long but feels longer when you’re holding a phone.)

The rebirth of the Flash intro in 2016’s mobile apps is partly due to new tools. As Flash was the pretty face that unleashed a thousand ugly intros, beautiful new mobile-oriented prototyping tools such as Principle have a strong focus on animation.

The downside of having great new tools is that designers don’t yet know what to do with them. Just like websites in 2001, most mobile apps really don’t need that much animation. But when animation tools is all you have, everything looks like it could be bouncing and swooping just a little bit more.

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Dead Men Write No Code


Dead Men Write No Code

I am a hypochondriac. In the back of my head I rationalize this as an evolutionary advantage. And in fact, it may have just saved my life.

I work long hours, in a chair, writing code (and of course this article applies to anyone who sits a lot). The sole reason I am writing this is to warn you of the danger you might be in if you are anything like me.

A couple of weeks ago, I got a pain in my lower left leg which almost felt like a sprain, but I knew I had not sprained it. It let it persist for about two weeks figuring that it would go away, but it did not. So, late at night I did what any hypochondriac does, I Googled it.

The first thing that came up was “Deep Vein Thrombosis” or DVT. From that article:

“ Blood clots (deep vein thrombosis DVT and pulmonary embolism PE) affect upwards of 600,000 Americans each year and cause more deaths each year than the more well-publicized occurrences of breast cancer, AIDS, and motor vehicle accidents, yet they are virtually unheard of.”

A DVT is a blood clot in a deep vein (your main circulatory system). The danger is that it can break free and flow to your lungs or heart, and will cause a pulmonary embolism (PE). How do you know if you are experiencing a PE? Well, one of the likely symptoms is that you will be dead.

I called in to my health care provider’s on-call nurse, and I was expecting the usual “probably nothing to worry about, schedule an appointment if it persists.” However, the nurse advised that I have someone drive me to the ER immediately.

The nurse had me coming to the ER based on a protocol that meant my life was potentially in danger, so that made me nervous. I had my blood drawn, x-rays taken, and then an ultrasound. The ultrasound detected some irregularities. It turned out that I had a clot in my system, but not in a deep vein. Such a clot is better than having a DVT, but that clot could have appeared anywhere (or migrated from a DVT), and it can still turn into a DVT or PE if not monitored and tended to. This was a warning shot that happened to hit my leg instead my head or chest. In the doctor’s own words, he told me I could “just as easily be dead right now.” I was lucky, but you might not even get a warning shot. The symptoms are not always clear, or even present for very long. Even if you survive a PE, it will adversely affect you the rest of your life.

The simple truth is that if you are getting blood clots in your 30s (I am 34), there is something horribly wrong with your lifestyle* and you are on the fast track to death, be it from cardiovascular disease or otherwise. Needless to say, this was a wake-up call for me. I had been blind-sided by my own work ethic, and frankly, selfish. Am I ready to leave my wife without a husband or my daughter without a father?

If you think you are not at risk for this because you are young and relatively healthy, let me break some news to you: I am young and “relatively healthy.” Let me explain what I mean by “relatively healthy” — my blood pressure is usually around 110/70, I walk at least 1–3 miles per day (sometimes more), I do push-ups and pull-ups very often (sometimes daily), my blood work checks out as completely normal in every respect (including low cholesterol), and prior to this my checkups revealed nothing abnormal.

However, you can’t go strictly by the numbers. What those numbers don’t reveal is that for the past 5 years I’ve spent the vast majority of it sitting, and very, very little of it with a significantly elevated heart rate.

I am overweight, but not extremely so — I weigh a bit over 200 and my ideal weight is more around 180. If you will forgive the douchey picture, this is me just 6 years ago, weighing 178:

Yes, its a little embarrassing to post this, but I really want to drive home the fact that even letting your health slip over a relatively short time can be dangerous (additional notes on my past exercise history at bottom). Looking at me, you wouldn’t likely tag me as someone who could die early (even at my current state at 20 pounds heavier). If this can happen to me, why not to you? If you think you are simply too young to get a DVT, I have seen cases occur to people in their early 20s.

I neglected my health for several years and I knew something bad was happening to my body. I would sit for up to 12 hours per day working, with small breaks here and there (mostly chores and walking my dogs). I’ve worked 80-hour weeks for the past decade (occasionally 100-hour weeks), but the past 5 years I have been particularly immobile. I have rationalized it with the “wealth before health” attitude that seems to be prevalent in the startup world (even though wealth is not my primary motivator, you get the idea). “I just need to make it through this year, and then I can exercise” and “exercise will kill my productivity” are two lies I have been telling myself for the past several years. I have taken a similar attitude with my diet, which is far from great.

Right now, if you are in my situation, seriously reconsider your life before its no longer an option. Nobody owns your life, and to those who think they do: you are more valuable to them as a healthy person than as a liability. Beyond that, I won’t go into giving you specific advice for being healthy, other than recommending sitting less (if that means getting a standing desk, that is one option)**.

Talk is cheap, and what good are my words if I can’t set an example? Starting tomorrow, I am drastically changing my diet and doing real cardio every day (i.e. running, not walking). I am not sitting until my feet hurt (I even wrote this article standing up). Even if it is embarrassing, I am having everyone hold me accountable and I am reporting my weight to social media every day (I’ll spare you the half-naked photos though until I am healthy again).

Additional Notes:

* As others have since pointed out, there are many potential causes of DTVs and clots, and while your health does play a large role, other things may effect people even in good health — flying and birth control are two common catalysts. I did fly one week prior to my first symptoms, so that was likely a contributing factor. However, I have taken many long flights without a resulting clot, and I think either way I would be less likely to have gotten a clot had I been healthier leading up to this. Even ignoring clots, it is generally good health advice to not sit for too long, exercise, and eat well.

** This is not just to fight off blood clots — sitting for too long is shown to have many adverse health effects, including negating the positive effects of exercise. Standing all day is also shown to be bad for you (if the studies are to be believed).

I am not nor do I claim to be an expert on any of these matters. I could easily be wrong about any given subject. As with anything, take the time to do your own additional research! :)

Notes on my past exercise habits since someone asked (I am omitting many other things I did like swimming, weight lifting, gymnastics, etc):

  • 1981–2000 (relatively active growing up, grew up in the outdoors, but never played sports outside of school)
  • 2000–2004 (ran 2–3 miles every single day, about 7 minutes per mile)
  • 2004–2006 (ran 1 to 2 times per week, same pace)
  • 2006–2008 (ran every day, about 2 miles, same pace)
  • 2008–2009 (did not run much but did a lot of other types of exercise, not much cardio)
  • 2009–2010 (ran 100+ flights of stairs per day, + 1–2 miles)
  • 2011 to present (cardio has gradually decreased to a point where I very rarely run, but I walk my dogs every single day 1–3 miles).

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.

Benefits of Cross-Functional Teams When Building Microservices

If you want your cross-functional teams to be successful, the first thing you need to do is to make sure that your organization can adapt. The software you create reinforces the culture of your company.

Agility is not the goal: it’s a method to solve a problem. Since the external environment can change faster than a company itself, it may need to change its pace as well. But it isn’t about sending out an email to all employees that the organization applies Scrum starting from next week: the transformation must happen on all levels. You need to make sure that there aren’t any roadblocks within your company that could slow down the speed of information. This applies to everything from feedback loops to knowledge centers that everyone can access, so they don’t need to spend time looking for the information they want to use.

Company culture must be prepared to support the transformation and adapt agile practices. Most people try to avoid being part of the ‘company transformation process’ since mass layoffs usually accompany it. Give people time to adapt and the resources to make it easier for them. Also, if you try to transform the middle managers into coaches first, they can support their colleagues well.

Functional vs cross-functional teams

A team completely owns a product during its whole lifetime. They don’t just create it, they are also responsible for maintaining it. This makes cross-functional teams perfect candidates for building microservices.

In project management, products are the formal definition of the project deliverables that make up or contribute to delivering the objectives of the project.

Separating teams by functions creates distance between them. If a separate QA team does the testing and developers are strictly focusing on writing code, they often don’t care much about testing and your product can end up with a lot of features that don’t work properly. A cross-functional team has individuals with different roles like database engineers, testers, infrastructure engineers, etc. As we can see from numerous examples (such as Amazon, Netflix, and Gilt for example), this can result in an excellent product that works as intended and the users love it.

Functional (or often called “siloed”) departments often adopt an “us vs. them” thinking against other teams. Instead of better productivity, this is more likely to result in hostility against each other. Working with people from different backgrounds also enables you to view the project from a different point of view. This helps understand the real reason behind a conflict and resolve (or even prevent) it.

Project: a piece of code that has to offer some predefined business value, must be handed over to the client, and is then periodically maintained by a team.

Cross-functional teams can ship code faster than functional teams because they can make their own decisions and work independently within an organization. The teams can focus on improving their cycle time and implement continuous deployment in order to solve the challenges they face almost instantly.

Teams can be formed by a manager or by the team itself. In both cases there is an important question that needs to be answered: how should people be grouped together? The two options are by similar function or by similar business.

Similar function

Grouping by similar function means that managers work with other managers, engineers with engineers, or marketers with fellow marketers. Melvin Conway’s law states that “Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.” This is as true today as it was half a century ago. These are called functional units. They work the best if you can manage to hire the best people to build a superb team of specialists who are truly experts in their own field. The similar community enables them to learn from each other to master their job. The biggest challenge is that departments usually have difficulties when communicating with each other. For example, if the task of the UI team is to do an overhaul of the interface but the backend guys are still in the middle of something else, then the whole project will be delayed until the backend tasks are done - since the UI team can't even start the project.

Watch out for these signals. Constantly ordering work across capabilities, splitting stories between teams, having to move people around towards tasks, deploying in lock-step and fan-in for end-to-end testing all mean that Conway’s law is in effect in your organization.

Similar business

In this case, the people work together to deliver the same business value: a new feature a new project, or even a new product.

The teams need to be stable enough to get the job done and in exchange, they can move faster and more efficiently than teams grouped by similar functions. The communication is more likely to be oriented around the goal itself and not around the communication or management issues
across functional units, making this approach more efficient.

Challenges

Nearly 75% of cross-functional teams have challenges with at least three of the following five criteria, according to Harvard Business Review:

  • meeting a planned budget
  • staying on schedule
  • adhering to specifications
  • meeting customer expectations
  • maintaining alignment with the company’s corporate goals

The Kanban community points out that reorganizing already established teams can cost a lot more without having a system to organize the tasks for the teams. Before you decide to reorganize your whole company it may be worth to take a look at what already works and what doesn’t. If the not-so-optimal pace of the organization originates from the confused state of tasks on a low-level, then the reorganization itself won’t do much.

Building microservices

Microservices should be:

  • cheap to replace;
  • quick to scale;
  • fault tolerant;

Above all: they should allow you to go as fast as possible.

Siloed teams spend weeks with iterations. Because the teams build tightly coupled services, manual tests need to be performed at the same time for all services. This is far from going fast: the tests can often last for weeks.

The first steps towards cross-functional teams

When building microservices, teams can be organized around a single business purpose, and focus on continuous delivery to skip the long-lasting test periods.

Continuous delivery is a software development discipline where you build software in such a way that the software can be released to production at any time.

To achieve this, you need a collaborative working environment for everyone involved in delivery. This environment is the first step to have cross-functional teams.

What it means in practice: merge architects, testers, operations and development teams into a single (no bigger than 10-20 people) cross-functional team. This way, teams don’t have to pass a project around until they get the feedback they need, and delivering services don’t need to happen once in weeks.

James Lewis recommends using these best practices on the different levels within your organization:

  • Top-layer, at the line of business (across the whole company)
    • semantic versioning (define a major version of the software that every team can use within the company)
  • Value streams (group of teams within an organization that can deliver business value to the customer)
    • semantic versioning
    • consumer-driven contract testing
  • Inter-team layer (relationship between the individual teams)
    • tolerant reader
    • consumer-driven contract testing

How to make cross-functional teams efficient

To make cross-functional teams truly effective, they have to be able to operate independently. This way, the unit can complete a project or even a whole feature without requiring regular coordination or micromanagement. Of course, you need to know about what’s going on, but if the goals are clearly set, you don’t need to interfere, and all the tasks get done in time. There can be someone that reports to the VP’s or C-level executives, but the QA managers and the other mid-level managers are not a must anymore.

Constant re-evaluation assures that you’re making progress. If the market changes faster than a project develops, it may be necessary to kill it to save precious resources and divert them to another project that could achieve greater results within the same period. It’s not an easy thing to do, but it’s not worth to chase something into a dead end only to find out that you need to turn back.

The optimal size of a microservice is not necessarily ‘micro’. Amazon uses the size that a ‘two-pizza team’ (around a dozen people) can maintain, but there are setups where half a dozen people support half a dozen services. The concept of self-contained systems suggests using services larger than a microservice but still small enough to keep a team busy and provide meaningful value.

Netflix

Netflix decided to go with highly aligned and loosely coupled teams. The company set clear, specific, and broadly understood goals. The interactions between teams are focused on strategy and objectives, not tactics. Although it requires a large investment in management time to be transparent, they feel it was worth it.

Their teams try to keep meetings at the minimum. This is possible because the teams truly trust each other - without requiring layers of approvals. The leaders reach out proactively to help whenever they feel it’s appropriate and don’t focus on supervising each task of the team members.

Cisco

Cross-functional teams need a good project manager more than anything else. Cisco implemented a 3-layer structure: a group of specialists working on their tasks, a smaller core of people who communicate back to their teams and two vice presidents at the top. The conclusion was that every project should have an end-to-end leader who oversees the whole operation, and the individual teams should also have a leader as well. If the goals are clearly established, this setup helps to make sure that the teams won’t miss them.

Takeaways

  • The success with microservices isn’t just about using the right cloud service or container system. Organizations that embrace cross-functional teams can scale more quickly than a company with siloed teams trying to move to a microservice-based architecture. The key for that is effective communication: the right information goes to the right place at the right time.
  • Teams building microservices need sophisticated monitoring and logging setups for each service to keep track of both operational and business metrics. Trace allows you to measure both.
  • Conway’s law creates a loop: teams not just create a software that mirrors the structure of the organization, but it also reinforces the existing hierarchy.
  • Open source projects are a good example to follow: people work together from different functions towards a mutual goal. These projects also follow Conway’s law and become modular and easy to scale.

Our recently published report aims to address questions of Node.js adoption into enterprise organizations for cross-functional teams.


Unit Test Your JavaScript Using Mocha and Chai

This article was peer reviewed by Panayiotis «pvgr» Velisarakos, Mark Brown and Tom Greco. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Have you ever made some changes to your code, and later found it caused something else to break?

I’m sure most of us have. This is almost inevitable, especially when you have a larger amount of code. One thing depends on another, and then changing it breaks something else as a result.

But what if that didn’t happen? What if you had a way of knowing when something breaks as a result of some change? That would be pretty great. You could modify your code without having to worry about breaking anything, you’d have fewer bugs and you’d spend less time debugging.

That’s where unit tests shine. They will automatically detect any problems in the code for you. Make a change, run your tests and if anything breaks, you’ll immediately know what happened, where the problem is and what the correct behavior should be. This completely eliminates any guesswork!

In this article, I’ll show you how to get started unit testing your JavaScript code. The examples and techniques shown in this article can be applied to both browser-based code and Node.js code.

The code for this tutorial is available from our GitHub repo.

What Is Unit Testing

When you test your codebase, you take a piece of code — typically a function — and verify it behaves correctly in a specific situation. Unit testing is a structured and automated way of doing this. As a result, the more tests you write, the bigger the benefit you receive. You will also have a greater level of confidence in your codebase as you continue to develop it.

The core idea with unit testing is to test a function’s behavior when giving it a certain set of inputs. You call a function with certain parameters, and check you got the correct result.

// Given 1 and 10 as inputs...
var result = Math.max(1, 10);

// ...we should receive 10 as the output
if(result !== 10) {
  throw new Error('Failed');
}

In practice, tests can sometimes be more complex. For example, if your function makes an Ajax request, the test needs some more set up, but the same principle of “given certain inputs, we expect a specific outcome” still applies.

For this article, we’ll be using Mocha. It’s easy to get started with, can be used for both browser-based testing and Node.js testing, and it plays nicely with other testing tools.

The easiest way to install Mocha is through npm (for which we also need to install Node.js). If you’re unsure about how to install either npm or Node on your system, consult our tutorial: A Beginner’s Guide to npm — the Node Package Manager

With Node installed, open up a terminal or command line in your project’s directory.

  • If you want to test code in the browser, run npm install mocha chai --save-dev
  • If you want to test Node.js code, in addition to the above, run npm install -g mocha

This installs the packages mocha and chai. Mocha is the library that allows us to run tests, and Chai contains some helpful functions that we’ll use to verify our test results.

Testing on Node.js vs Testing in the Browser

The examples that follow are designed to work if running the tests in a browser. If you want to unit test your Node.js application, follow these steps.

  • For Node, you don’t need the test runner file.
  • To include Chai, add var chai = require('chai'); at the top of the test file.
  • Run the tests using the mocha command, instead of opening a browser.

Setting up a Directory Structure

You should put your tests in a separate directory from your main code files. This makes it easier to structure them, for example if you want to add other types of tests in the future (such as integration tests or functional tests).

The most popular practice with JavaScript code is to have a directory called test/ in your project’s root directory. Then, each test file is placed under test/someModuleTest.js. Optionally, you can also use directories inside test/, but I recommend keeping things simple — you can always change it later if necessary.

Setting up a Test Runner

In order to run our tests in a browser, we need to set up a simple HTML page to be our test runner page. The page loads Mocha, the testing libraries and our actual test files. To run the tests, we’ll simply open the runner in a browser.

If you’re using Node.js, you can skip this step. Node.js unit tests can be run using the command mocha, assuming you’ve followed the recommended directory structure.

Below is the code we’ll use for the test runner. I’ll save this file as testrunner.html.

<!DOCTYPE html>
<html>
  <head>
    <title>Mocha Tests</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
  </head>
  <body>
    <div id="mocha"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- load code you want to test here -->

    <!-- load your test files here -->

    <script>
      mocha.run();
    </script>
  </body>
</html>

The important bits in the test runner are:

  • We load Mocha’s CSS styles to give our test results nice formatting.
  • We create a div with the ID mocha. This is where the test results are inserted.
  • We load Mocha and Chai. They are located in subfolders of the node_modules folder since we installed them via npm.
  • By calling mocha.setup, we make Mocha’s testing helpers available.
  • Then, we load the code we want to test and the test files. We don’t have anything here just yet.
  • Last, we call mocha.run to run the tests. Make sure you call this after loading the source and test files.

The Basic Test Building Blocks

Now that we can run tests, let’s start writing some.

We’ll begin by creating a new file test/arrayTest.js. An individual test file such as this one is known as a test case. I’m calling it arrayTest.js because for this example, we’ll be testing some basic array functionality.

Every test case file follows the same basic pattern. First, you have a describe block:

describe('Array', function() {
  // Further code for tests goes here
});

describe is used to group individual tests. The first parameter should indicate what we’re testing — in this case, since we’re going to test array functions, I’ve passed in the string 'Array'.

Secondly, inside the describe, we’ll have it blocks:

describe('Array', function() {
  it('should start empty', function() {
    // Test implementation goes here
  });

  // We can have more its here
});

it is used to create the actual tests. The first parameter to it should provide a human-readable description of the test. For example, we can read the above as “it should start empty”, which is a good description of how arrays should behave. The code to implement the test is then written inside the function passed to it.

All Mocha tests are built from these same building blocks, and they follow this same basic pattern.

  • First, we use describe to say what we’re testing – for example, “describe how array should work”.
  • Then, we use a number of it functions to create the individual tests – each it should explain one specific behavior, such as “it should start empty” for our array case above.

Writing the Test Code

Now that we know how to structure the test case, let’s jump into the fun part — implementing the test.

Since we are testing that an array should start empty, we need to create an array and then ensure it’s empty. The implementation for this test is quite simple:

var assert = chai.assert;

describe('Array', function() {
  it('should start empty', function() {
    var arr = [];

    assert.equal(arr.length, 0);
  });
});

Note on the first line, we set up the assert variable. This is just so we don’t need to keep typing chai.assert everywhere.

In the it function, we create an array and check its length. Although simple, this is a good example of how tests work.

First, you have something you’re testing — this is called the System Under Test or SUT. Then, if necessary, you do something with the SUT. In this test, we’re not doing anything, since we’re checking the array starts as empty.

The last thing in a test should be the validation — an assertion which checks the result. Here, we are using assert.equal to do this. Most assertion functions take parameters in the same order: First the “actual” value, and then the “expected” value.

  • The actual value is the result from your test code, so in this case arr.length
  • The expected value is what the result should be. Since an array should begin empty, the expected value in this test is 0

Chai also offers two different styles of writing assertions, but we’re using assert to keep things simple for now. When you become more experienced with writing tests, you might want to use the expect assertions instead, as they provide some more flexibility.

Running the Test

In order to run this test, we need to add it to the test runner file we created earlier.

If you’re using Node.js, you can skip this step, and use the command mocha to run the test. You’ll see the test results in the terminal.

Otherwise, to add this test to the runner, simply add:

<script src="test/arrayTest.js"></script>

Below:

<!-- load your test files here -->

Once you’ve added the script, you can then load the test runner page in your browser of choice.

The Test Results

When you run your tests, the test results will look something like this:

Mocha test results - 1 test passing

Note that what we entered into the describe and it functions show up in the output — the tests are grouped under the description. Note that it’s also possible to nest describe blocks to create further sub-groupings.

Let’s take a look at what a failing test looks like.

On the line in the test that says:

assert.equal(arr.length, 0);

Replace the number 0 with 1. This makes the test fail, as the array’s length no longer matches the expected value.

If you run the tests again, you’ll see the failing test in red with a description of what went wrong.

Mocha test error - one test failing

One of the benefits of tests is that they help you find bugs quicker, however this error is not very helpful in that respect. We can fix it though.

Most of the assertion functions can also take an optional message parameter. This is the message that is displayed when the assertion fails. It’s a good idea to use this parameter to make the error message easier to understand.

We can add a message to our assertion like so:

assert.equal(arr.length, 1, 'Array length was not 0');

If you re-run tests, the custom message will appear instead of the default.

Let’s switch the assertion back to the way it was — replace 1 with 0, and run the tests again to make sure they pass.

Putting It Together

So far we’ve looked at fairly simple examples. Let’s put what we’ve learned into practice and see how we would test a more realistic piece of code.

Here’s a function which adds a CSS class to an element. This should go in a new file js/className.js.

function addClass(el, newClass) {
  if(el.className.indexOf(newClass) === -1) {
    el.className += newClass;
  }
}

To make it a bit more interesting, I made it add a new class only when that class doesn’t exist in an element’s className property — who wants to see <div class="hello hello hello hello"> after all?

In the best case, we would write tests for this function before we write the code. But test-driven development is a complex topic, and for now we just want to focus on writing tests.

To get started, let’s recall the basic idea behind unit tests: We give the function certain inputs and then verify the function behaves as expected. So what are the inputs and behaviors for this function?

Given an element and a class name:

  • if the element’s className property does not contain the class name, it should be added.
  • if the element’s className property does contain the class name, it should not be added.

Let’s translate these cases into two tests. In the test directory, create a new file classNameTest.js and add the following:

describe('addClass', function() {
  it('should add class to element');
  it('should not add a class which already exists');
});

We changed the wording slightly to the “it should do X” form used with tests. This means that it reads a bit nicer, but is essentially still the same human-readable form we listed above. It’s usually not much more difficult than this to go from idea to test.

But wait, where are the test functions? Well, when we omit the second parameter to it, Mocha marks these tests as pending in the test results. This is a convenient way to set up a number of tests — kind of like a todo list of what you intend to write.

Let’s continue by implementing the first test.

describe('addClass', function() {
  it('should add class to element', function() {
    var element = { className: '' };

    addClass(element, 'test-class');

    assert.equal(element.className, 'test-class');
  });

  it('should not add a class which already exists');
});

In this test, we create an element variable and pass it as a parameter to the addClass function, along with a string test-class (the new class to add). Then, we check the class is included in the value using an assertion.

Again, we went from our initial idea — given an element and a class name, it should be added into the class list — and translated it into code in a fairly straightforward manner.

Although this function is designed to work with DOM elements, we’re using a plain JS object here. Sometimes we can make use of JavaScript’s dynamic nature in this fashion to simplify our tests. If we didn’t do this, we would need to create an actual element and it would complicate our test code. As an additional benefit, since we don’t use DOM, we can also run this test within Node.js if we so wish.

Running the Tests in the Browser

To run the test in the browser, you’ll need to add className.js and classNameTest.js to the runner:

<!-- load code you want to test here -->
<script src="js/className.js"></script>

<!-- load your test files here -->
<script src="test/classNameTest.js"></script>

You should now see one test pass and another test show up as pending, as is demonstrated by the following CodePen. Note that the code differs slightly from the example in order to make the code work within the CodePen environment.

See the Pen Unit Testing with Mocha (1) by SitePoint (@SitePoint) on CodePen.

Next, let’s implement the second test…

it('should not add a class which already exists', function() {
  var element = { className: 'exists' };

  addClass(element, 'exists');

  var numClasses = element.className.split(' ').length;
  assert.equal(numClasses, 1);
});

It’s a good habit to run your tests often, so let’s check what happens if we run the tests now. As expected, they should pass.

Here’s another CodePen with the second test implemented.

See the Pen Unit Testing with Mocha (2) by SitePoint (@SitePoint) on CodePen.

But hang on! I actually tricked you a bit. There is a third behavior for this function which we haven’t considered. There is also a bug in the function — a fairly serious one. It’s only a three line function but did you notice it?

Let’s write one more test for the third behavior which exposes the bug as a bonus.

it('should append new class after existing one', function() {
  var element = { className: 'exists' };

  addClass(element, 'new-class');

  var classes = element.className.split(' ');
  assert.equal(classes[1], 'new-class');
});

This time the test fails. You can see it in action in the following CodePen. The problem here is simple: CSS class names in elements should be separated by a space. However, our current implementation of addClass doesn’t add a space!

See the Pen Unit Testing with Mocha (3) by SitePoint (@SitePoint) on CodePen.

Let’s fix the function and make the test pass.

function addClass(el, newClass) {
  if(el.className.indexOf(newClass) !== -1) {
    return;
  }

  if(el.className !== '') {
    //ensure class names are separated by a space
    newClass = ' ' + newClass;
  }

  el.className += newClass;
}

And here’s a final CodePen with the fixed function and passing tests.

See the Pen Unit Testing with Mocha (4) by SitePoint (@SitePoint) on CodePen.

Running the Tests on Node

In Node, things are only visible to other things in the same file. As className.js and classNameTest.js are in different files, we need to find a way to expose one to the other. The standard way to do this is through the use of module.exports. If you need a refresher, you can read all about that here: Understanding module.exports and exports in Node.js

The code essentially stays the same, but is structured slightly differently:

// className.js

module.exports = {
  addClass: function(el, newClass) {
    if(el.className.indexOf(newClass) !== -1) {
      return;
    }

    if(el.className !== '') {
      //ensure class names are separated by a space
      newClass = ' ' + newClass;
    }

    el.className += newClass;
  }
}


// classNameTest.js

var chai = require('chai');
var assert = chai.assert;

var className = require('../js/className.js');
var addClass = className.addClass;

// The rest of the file remains the same

describe('addClass', function() {
  ...
});

And as you can see, the tests pass.

Mocha terminal output - 4 tests passing

What’s Next?

As you can see, testing does not have to be complicated or difficult. Just as with other aspects of writing JavaScript apps, you have some basic patterns which repeat. Once you get familiar with those, you can keep using them again and again.

But this is just scratching the surface. There’s a lot more to learn about unit testing.

  • Testing more complex systems
  • How to deal with Ajax, databases, and other “external” things?
  • Test-Driven Development

If you want to continue learning this and more, I’ve created a free JavaScript unit testing quickstart series. If you found this article useful, you should definitely check it out here.