Created
September 30, 2016 19:22
-
-
Save rjz/4c6922b811a6ea859b19ed62a682045c to your computer and use it in GitHub Desktop.
Testing with fetch, fetchmock, and TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example of mocking out global `fetch` | |
// | |
// Spec works using Jasmine (via Karma) and _either_ tsc or babel. | |
// | |
// $ npm install --save-dev fetch-mock whatwg-fetch | |
// | |
// If using `tsc`, grab the type definitions as well: | |
// | |
// $ typings --save --global dt~fetch-mock dt~whatwg-fetch | |
import * as fetchMock from 'fetch-mock' | |
// `projects` wraps REST methods against the hypothetical API resource | |
import { projects } from './api' | |
describe('api/projects', () => { | |
afterEach(fetchMock.restore) | |
describe('.list', () => { | |
describe('valid JSON', () => { | |
it('returns project list', (done) => { | |
fetchMock.mock('/api/v1/projects', { | |
status: 200, | |
body: { | |
data: [ | |
{ id: 1 }, | |
], | |
}, | |
}) | |
projects.list() | |
.then((x) => { | |
expect(x.data.length).toEqual(1) | |
done() | |
}) | |
.catch(done.fail) | |
}) | |
}) | |
describe('invalid JSON', () => { | |
it('throws an error', (done) => { | |
fetchMock.mock('/api/v1/projects', 200) | |
projects.list() | |
.catch((err) => { | |
expect(err instanceof Error).toEqual(true) | |
expect(err.toString()).toMatch(/JSON Parse error/) | |
done() | |
}) | |
}) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
doesnt work for me :(