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:

 1import faq from "./faq";
 2
 3describe("faq", () => {
 4  it("is able to handle the add faq item action", () => {
 5    expect(
 6      faq([], {
 7        type: "ADD_FAQ_ITEM",
 8        question: "What is the answer to life the universe and everything?",
 9        answer: 42
10      })
11    ).toEqual([{
12      question: "What is the answer to life the universe and everything?",
13      answer: 42
14    }]);
15  });
16});

13.2. Exercise

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

Solution

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