Chapter 8. Organizing tests with factory functions


This chapter covers

  • Understanding factory functions
  • Using factory functions to organize tests

As a test suite grows in size, you start to see repeated code. One way to avoid this is to use factory functions to organize tests.

Factory functions are functions that return new objects or instances (you might know them as builders). You can add factory functions to tests that require repetitive setup to remove code duplication.

Using factory functions is a pattern that helps keep test code easy to read and understand. In this chapter, you’ll learn what factory functions are, how they can reduce repetition in tests, and how they improve your test code structure.

After you’ve learned what factory functions are and the benefits that they bring, you’ll refactor the test code in ItemList.vue to use factory functions.

8.1. Understanding factory functions

Factory functions make it easier to create objects by extracting the logic used to create the objects into a function. The best way to explain factory functions is with an example. Imagine you were writing tests for a component that used a Vue instance $t property. Each time you created a wrapper with Vue Test Utils, you would need to mock the $t function, as shown in the next listing.

Listing 8.1. Creating a wrapper object
const wrapper = shallowMount(TestComponent, {
  mocks: {
    $t: () => {}

8.2. Creating a store factory function

8.3. Overwriting default options in factory functions

8.4. Creating a wrapper factory function