Run the Docs' Examples as Tests

In the last lesson, you found where your reference and Niamh’s changed server disagree by running every curl example by hand. Her own tests all passed because they check what Niamh expects. None of them checks what docs/api.md promises Joon-ho.

In this lesson, you’ll make the test suite run the reference’s examples for you, so npm test fails as soon as an example stops matching the server. Start by turning one example into values a test can send.

Keep an Example as Data

A curl example in docs/api.md is text for people, and a test can’t send it. A test needs the example’s parts as values: the method, the path, any body, and the status and body the reference promises. Create docs/examples.ts, next to api.md, with the values of the GET /shows/6 example copied from the reference exactly as written:

Language: TypeScript Filename: docs/examples.ts
// The reference's examples, run by examples.test.ts.
export type Example = {
  name: string;
  method: "GET" | "POST" | "PATCH" | "DELETE";
  path: string;
  body?: unknown;
  status: number;
  response?: unknown;
};

export const examples: Example[] = [
  {
    name: "GET /shows/6 gets one show",
    method: "GET",
    path: "/shows/6",
    status: 200,
    response: {
      id: "6",
      title: "The Sunday Request Show",
      host: "Gloria Mendes",
      day: "Sunday",
      start: "10:00",
      minutes: 120,
    },
  },
];

The Example type names the parts of each example in an examples module: a file of request and response pairs that a test can import, as you’d import any value another module exports. The body and response fields are optional because a GET request sends no body and a 204 answers with none. Each example’s name becomes its test’s name.

Run Every Example as a Test

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.