Skip to content

Instantly share code, notes, and snippets.

@rjz
Created September 30, 2016 19:22
Show Gist options
  • Save rjz/4c6922b811a6ea859b19ed62a682045c to your computer and use it in GitHub Desktop.
Save rjz/4c6922b811a6ea859b19ed62a682045c to your computer and use it in GitHub Desktop.
Testing with fetch, fetchmock, and TypeScript
// 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()
})
})
})
})
})
@holylander
Copy link

doesnt work for me :(

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "t
...

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