jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

Inspecting fetch URL and options #55

Closed robcaldecott closed 6 years ago

robcaldecott commented 6 years ago

When testing it would sometimes be useful to inspect the fetch URL and options being passed: checking for the correct headers, POST body content, etc. Is there any way to achieve this using jest-fetch-mock?

jefflau commented 6 years ago

Hi @robcaldecott

jest-fetch-mock does support it because the jest mocks underlying architecture supports it. I probably need to document it better, but it works the same way jest mocks work. You can copy these two files api.js and api.test.js into your project to see how it works. The docs for mocks in jest are here: https://facebook.github.io/jest/docs/en/mock-functions.html

//api.js
import 'isomorphic-fetch';

export function getStuff() {
  return fetch('https://facebook.com').then(stuff => {
    console.log(stuff);
  });
}
//api.test.js
import { getStuff } from './api';

it('mock test', () => {
  const mock = fetch.mockResponse(JSON.stringify({ access_token: '12345' }));
  getStuff();

  console.log(fetch.mock.calls);

  expect(fetch.mock.calls.length).toEqual(1);
  expect(fetch.mock.calls[0][0]).toEqual('https://facebook.com');

  fetch.resetMocks();

  console.log(fetch.mock.calls);
});
robcaldecott commented 6 years ago

Of course. I should have worked that out. :) Many thanks! Works perfectly.

jefflau commented 6 years ago

Cool :) My fault. I should have documented better.

Sorry for the slow reply. Hope it works good now!

I'll leave this issue up until I get the documentation sorted out

jefflau commented 6 years ago

Added documentation to this so hopefully it won't be an issue. Closing this!