Skip to content

Instantly share code, notes, and snippets.

@bnguyensn
Last active August 29, 2019 08:17
Show Gist options
  • Save bnguyensn/8322d77197464bd9d5997cf264bc84ab to your computer and use it in GitHub Desktop.
Save bnguyensn/8322d77197464bd9d5997cf264bc84ab to your computer and use it in GitHub Desktop.
Jest notes

Jest

Mock

Mocking web APIs

Basic example

An example of how you could mock the fetch() function:

/// abc.test.js

window.fetch = jest
  .fn(() => (
    Promise.resolve({
      ok: true,
      json: () => {count: 1}
    })
  ));

By doing this, anytime any function makes a call to fetch(), Jest will run the mocked version above instead, returning a mock result object.

One step further

Taking this one step further:

/// abc.test.js

window.fetch = jest
  .fn()
  .mockImplementationOnce(() =>
    Promise.resolve({
      ok: true,
      json: () => {count: 1},
    })
  )
  .mockImplementationOnce(() =>
    Promise.resolve({
      ok: false,
      status: 404,
      statusText: "Not Found",
    })
  );

Doing this allows us to test for different fetch result cases (success and failure).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment