slack splash

The unmock docs

Unmock is currently in public beta. Check this page regularly for exciting new features.

Once you've gotten your unmock key, you are ready to follow these docs. If you have not yet gotten a key, click here. Otherwise, read on!


Installing unmock

If you have not yet retrieved your unmock key, click here. Once retrieved, you need to install it in the root of your project in a file called .unmock/credentials. For example, your project structure could look like this.

src/
  index.ts
__test__/
  index.test.ts
.unmock/
  credentials

The credentials file itself should have the following structure.

[unmock]
token=my-client-secret

Your credential is private, so please do not share it with anyone else. To use the credential in a continuous integration environment, simply store it in an environmental variable and write it to this file as a build step before the tests are run.


Writing your first test

tl;dr github repo click here

For this quick start, we will use unmock to mock a simple call to the Behance API. We'll use typescript for this project, but you can also use plain old javascript.

First, create a directory for this quick start and run the following commands:

yarn init -y
yarn add axios
yarn add -D typescript jest @types/node @types/jest tslint ts-jest unmock
yarn tsc --init && yarn tslint --init && yarn ts-jest config:init
mkdir src && mkdir test

In your generated tsconfig.json, make sure to set "lib": ["es2015"] so that you can use modern async/await syntax. Also, in your package.json file, make sure to include an entry for the test script.

"scripts": {
    "test": "jest"
}

Once this is done, create a file called src/index.ts with the following content.

import axios from "axios";
export const getProject = async (projectId: number) => {
  const key = process.env.BEHANCE_API_KEY;
  const { data } = await axios(`https://www.behance.net/v2/projects/${projectId}/?api_key=${key}`);
  return data;
};
And then write the corresponding test.
import { getProject } from "../src/";

test("get project", async () => {
  process.env.API_KEY = "u_n_m_o_c_k_200";
  const project = await getProject(123);
  expect(project.id).toBe(123);
});

Let's see what happens if you run yarn test without unmock.

$ yarn test
yarn run v1.12.3
$ jest
 FAIL  test/index.test.ts
  ✕ get project (549ms)

  ● get project

    Request failed with status code 403

      at createError (node_modules/axios/lib/core/createError.js:16:15)
      at settle (node_modules/axios/lib/core/settle.js:18:12)
      at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:201:11)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.436s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Not surprisingly, the test fails. In general, this strategy is bad for a few reasons.

  • You have not used a real API key.
  • Even with a real API key, you would run into rate-limiting.
  • Storing production API keys on your local machine is a bad idea.
  • You may accidentally modify your production environemnt from the tests.

The last one is particularly important to remember. You are writing tests to make sure your code is not broken, and if it is, it will call external APIs in a broken way. This can have catastrophic effects on your app, including accidentally spamming users, deleting users, or mishandling their data.

With unmock

import { getProject } from "../src/";
import { kcomnu, unmock } from "unmock";

beforeEach(async () => await unmock()); // <- start unmock
afterEach(async () => await kcomnu()); // <- end unmock
test("get project", async () => {
  process.env.API_KEY = "u_n_m_o_c_k_200";
  const project = await getProject(123);
  expect(project.id).toBe(123);
});
  

Now let's run that test again.

$ yarn test
yarn run v1.12.3
$ jest
 PASS  test/index.test.ts (5.534s)
  ✓ get project (3304ms)

unmock: *****url-called*****
unmock: Hi! We see you've called get www.behance.net/v2/projects/123/?api_key=undefined.
unmock: We've sent you mock data back. You can edit your mock at https://unmock.io/x/1fc911b5. 🚀
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.587s
Ran all test suites.
✨  Done in 6.81s.

Magic. Unmock takes care of mocking the Behance API and sends you back semantically correct test data. In this particular example, the id returned by unmock is the one used to make the API call. In general, unmock uses AI in order to make sure that mocked APIs return semantically correct data, including data persisted between calls to the same mocked API.


Editing your mock

Sometimes, your mocked response needs to contain data that unmock cannot provide. This can happen for a variety of reasons.

  • There is an initial state of mocked data that unmock cannot capture
  • There are particular corner cases you need to test for a given mock, such as empty strings or null values in responses.
  • Unmock does not mock the API yet.

In all of these cases, you can edit your mock directly from the unmock web dashboard. The url at which your mock lives is printed to the console during tests and is also listed on unmock.io/app once you have gotten your API key. For example, if in the example above we want to change the project's name, we can do that here.

img

Tweaking mocks

Sometimes, editing static data is not enough. Unmock allows you to "tweak" mocks with micro-serverless functions. The function takes a single array representing the history of previous mocks, with the current mock as the first element of the array. For example, to change the created_on value to a current timestamp, you can do the following.

img

Testing errors

This feature is currently in private alpha. Coming to the unmock beta in Feburary 2019.

One of the most important and, unfortunately, least tested aspects of any app is error handling from 3rd part integrations. Unmock makes this easy using the u_n_m_o_c_k_XXX naming convention.

You may remember that, in the previous example, we set the Behance API Key to u_n_m_o_c_k_200. Unmock automatically identifies the API key being used and, in the absence of a key (for example, if the API is public) grabs the key from the Authorization header using the Bearer scheme. The key is always in the form u_n_m_o_c_k_XXX, where XXX is the HTML return code. For example, to provoke a 404 Not Found request from the Behance API, use the key u_n_m_o_c_k_404.

test("get project throws 400", async () => {
  expect(() => {
    process.env.API_KEY = "u_n_m_o_c_k_404";
    const project = await getProject(123);
  }).toThrow();
});
  

Now let's run that test again.

... something ...

Custom APIs

This feature is currently in private alpha. Coming to the unmock beta in March 2019.

Unmock supports uploading custom APIs in the form of GraphQL or Swagger specifications and will generate mock data for these APIs using the same AI engine it uses to mock third-party APIs. To upload your own API to unmock, make sure you install the unmock cli and run unmock from the root directory of a project that contains your unmock credential in the .unmock/credentials file.

$ yarn add -g unmock
$ unmock https://www.mysite.com/my_swagger_file.json https://api.mysite.com

CircleCI

Unmock proudly participates in the CircleCI orb program in order to help our users sign their unmock requests and use their unmock token with ease.

To use the unmock orb, simply add an unmock/credentials to your .circleci/config.yml file A short snippet is provided below for your reference, and a more detailed example of how to do this is hosted on the CircleCI orb registry.

version: 2.1
orbs:
  unmock: unmock/unmock@0.0.7
jobs:
  build:
    steps:
      - unmock/credentials:
          token: my-unmock-token
      - run: yarn install
      - run: yarn test

Community + Questions

The unmock community Slack workspace is a place where unmock builders unite to help grow the service and share learnings. It is also where major announcements are made and where you can directly influence our roadmap. To join the unmock community workspace, click on the link below. For all other questions, use the intercom widget on the bottom-right corner of this page to reach out to our support desk.

Join our community