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.

Revisions

  1. rjz created this gist Sep 30, 2016.
    54 changes: 54 additions & 0 deletions projects_spec.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    // 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()
    })
    })
    })
    })
    })