Skip to content

Instantly share code, notes, and snippets.

@damon-kreft
Last active March 29, 2017 12:44
Show Gist options
  • Save damon-kreft/95cd3311b906bbddf446cb0e8a3c3dbf to your computer and use it in GitHub Desktop.
Save damon-kreft/95cd3311b906bbddf446cb0e8a3c3dbf to your computer and use it in GitHub Desktop.
Unit Testing Using Mocked Imports
// A simple isomorphic-fetch mock that returns what you pass into it so we can assert that the methods in products.js
// are passing the correct values (I'd add rejection logic in here too to test those cases but this is just for demo purposes)
const fetch = (url, options) => {
return Promise.resolve({url, options});
};
export default fetch;
// Super simple module for fetching product data
import fetch from 'isomorphic-fetch';
export const defaultOptions = {
headers: {
'Content-Type': 'application/json'
}
};
const mergeOptions = (...options) => {
return Object.assign({}, defaultOptions, ...options);
};
export const getProduct = (id, options = {}) => {
return fetch(`http://localhost/product/${id}`, mergeOptions(options));
};
export const getProducts(options = {}) => {
return fetch('http://localhost/products', mergeOptions(options));
};
// A test that mocks the isomorphic-fetch import inside products.js
import {
getProduct,
getProducts,
defaultOptions
} from './products';
jest.mock('isomorphic-fetch', () => { // <-- the explicit mock of fetch
return require('./isomorphic-fetch-mock');
});
describe.only('products.js', () => {
it('getProduct(id, options)', (cb) => {
const expected = {
url: 'http://localhost/product/1',
options: Object.assign({}, defaultOptions, {
testy: 'westy'
})
};
getProduct(1, {testy: 'westy'}).then((result) => {
expect(result).toEqual(expected);
cb();
});
});
it('getProducts(options)', (cb) => {
const expected = {
url: 'http://localhost/products',
options: Object.assign({}, defaultOptions, {
testy: 'westy'
})
};
getProducts({testy: 'westy'}).then((result) => {
expect(result).toEqual(expected);
cb();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment