13. Write Tests For Your Reducers

13.1. Reducer Tests

Since reducers are pure functions with input and output we can write unit tests for them. We will start by adding a test for the ADD_TODO action in a file called reducers/faq.test.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import faq from "./faq";

describe("faq", () => {
  it("is able to handle the add faq item action", () => {
    expect(
      faq([], {
        type: "ADD_FAQ_ITEM",
        question: "What is the answer to life the universe and everything?",
        answer: 42
      })
    ).toEqual([{
      question: "What is the answer to life the universe and everything?",
      answer: 42
    }]);
  });
});

13.2. Exercise

Add the unit tests for the edit and the delete actions for the reducer.

Solution

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
it("is able to handle the edit faq item action", () => {
  expect(
    faq(
      [{
        question: "What is the answer to life the universe and everything?",
        answer: 42
      }], {
        type: "EDIT_FAQ_ITEM",
        index: 0,
        question: "What is the answer to life the universe and everything?",
        answer: 43
      }
    )
  ).toEqual([{
    question: "What is the answer to life the universe and everything?",
    answer: 43
  }]);
});

it("is able to handle the delete faq item action", () => {
  expect(
    faq(
      [{
        question: "What is the answer to life the universe and everything?",
        answer: 42
      }], {
        type: "DELETE_FAQ_ITEM",
        index: 0
      }
    )
  ).toEqual([]);
});