Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Last active October 4, 2018 17:30
Show Gist options
  • Save ricardocanelas/3dcc26a56b8d1aab7af522dca9fc6b53 to your computer and use it in GitHub Desktop.
Save ricardocanelas/3dcc26a56b8d1aab7af522dca9fc6b53 to your computer and use it in GitHub Desktop.
React - Mock

package.json

"devDependencies": {
    "enzyme": "^3.3.0",
    "enzyme-adapter-react-16": "^1.1.1",
    "jest-fetch-mock": "^1.4.2",
    "sinon": "^4.4.2",
    "source-map-explorer": "^1.5.0"
},
"scripts": {
    "test": "react-scripts test --env=jsdom",
    "analyze": "source-map-explorer build/static/js/main.*",
}

src/setupTests.js

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import JestFetchMock from 'jest-fetch-mock'

configure({ adapter: new Adapter() });

global.fetch = JestFetchMock


class LocalStorageMock {
    constructor() {
      this.store = {};
    }
  
    clear() {
      this.store = {};
    }
  
    getItem(key) {
      return this.store[key] || null;
    }
  
    setItem(key, value) {
      this.store[key] = value.toString();
    }
  
    removeItem(key) {
      delete this.store[key];
    }
};
  
global.localStorage = new LocalStorageMock;

/src/components/MyComp.test.js

// External depedencies
import React from 'react';
import { shallow, mount } from 'enzyme';

// Our depedencies
import Search from './Search';

const fakeBook = {
    id: "ZYzsjxrtpLsC",
    title: "American Yiddish Poetry",
    subtitle: "A Bilingual Anthology",
    description: "Provides information on the Yiddish language and literature, describes poetic forms, and gathers poems in Yiddish and English by seven of the best Jewish American poets",
    shelf: "currentlyReading",    
    imageLinks: {
        smallThumbnail: "smallThumbnail.jpg",
        thumbnail: "thumnail.jpg"
    },
    authors: [
        "Benjamin Harshav", "Barbara Harshav"
    ],
    infoLink: "http://books.google.com/books?id=ZYzsjxrtpLsC&dq=poetry&hl=&source=gbs_api",
    language: "en",
    pageCount: "813",
    publishedDate: "1986"
}

describe('View: <Search />', () => {

    beforeEach(() => {
        fetch.mockResponse(JSON.stringify({books: [fakeBook]}))
    });

    it('renders without crashing', () => {
        expect(shallow(<Search />))
    });

    it('mounts without crashing', () => {
        expect(mount(<Search />))
    });

    it('is another test', () => {
        //...
    });
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment