API Mocks

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-25
Updated:
2019-08-15
Tags:
React libraries JavaScript testing

https://frontendmasters.com/courses/intermediate-react-v2/api-mocks/

Handling Ajax calls

We are going to write a manual mock ourselves.

Creates another folder __mocks__, and inside pet.js The name is important, it denotes, the API that we are mocking.

  //    ****        __mocks__/pet.js        ****

import { readFileSync } from "fs";
import path from "path";
// act helps to keep track of when
// react needs to rerender
import { act } from "react-testing-library";

// some mock data
const breeds = [
  { name: "Bichon Frise" },
  { name: "Bolognese" },
  { name: "Bolonka" },
  { name: "Coton de Tulear" },
  { name: "Havanese" },
  { name: "Lowchen" },
  { name: "Maltese" }
];

// get some mock data from an "API"
// adds the res.json file ...
const doggos = JSON.parse(
  // making sure to get the right file from the right dir
  readFileSync(path.join(__dirname, "/res.json")).toString()
);

// animal types
export const ANIMALS = ["dog", "cat", "bird"];
// export the breeds
// the "_" underscore means it's for testing only
export const _breeds = breeds;
export const _dogs = doggos.animals;

// create a simple mock library
const mock = {
 // jest.fn is a spy function
 // breeds is a "fake", spy function
  breeds: jest.fn(() => {
   // meaning whenever someone calls this function
   // return this promise like object below ↴
    return {
      then: callback =>
      // this notifies React, 
      // that we updated something
        act(() => {
          callback({
            breeds: breeds
          });
        })
    };
  }),
  // another function 
  animals: jest.fn(() => {
    return {
      then: callback =>
        act(() => {
          callback(doggos);
        })
    };
  })
};

export default mock;

With the above naming convention (__mocks__/pet.js), anytime someone imports the real @frontendmasters/pets library, Jest will automatically mock it.

tell ESLint about jest

  --- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -24,7 +24,8 @@
   "env": {
     "es6": true,
     "browser": true,
-    "node": true
+    "node": true,
+    "jest": true
   },
   "settings": {
     "react": {