Test-Driven Development Guided Lab: Mocking External Dependencies

Solution Overview

Testing code that depends on information from external sources is one of the more challenging problems a software engineer will face. How do you go about automating tests when the data returned by a service dependency may change from moment to moment? How do you deal with network/database issues that arise during automated testing? If you need to test the behavior of your code under error conditions, how do you mimic that environment?

External dependencies can be handled by designing the application in such a way that the dependencies can be replaced by "mock" objects during testing. These mock objects respond to the requests the application makes in reliable ways and can be used to test both standard and error conditions.

This lab will teach the process of creating and providing mock objects when testing code that depends on external sources of information. This will be accomplished by guiding the user through the implementation of a fictitious point of sale application.


This lab requires a working knowledge of JavaScript (specifically ECMA Script 6) syntax. It can be launched by anyone who is interested in the content of the lab, however it may be challenging to get the tests to pass without some prior debugging experience. There are a few key points in the lab where more complete code blocks are provided that should get you back on-track if things are not working as expected.

Goals & Objectives

Through this lab you will learn a number of concepts that relate to the testing/implementing of code that has external dependencies:

  • How to write tests that drive the architecture/function of code.
  • Mock objects and the differences between stubs, mocks and fakes.
  • How to create your own mock object to satisfy dependencies.
  • How to use a mocking framework to create mocks.
  • How to implement dependency injection using a constructor.

Hardware & Software

  • JavaScript (ECMA Script 6)
  • Node.js
  • Mocha
  • Chai.js
  • Sinon.js