Skip to content

Instantly share code, notes, and snippets.

@cowchimp
Created December 12, 2017 13:25
Show Gist options
  • Save cowchimp/0158efe57df3b845927e450fc2b87eeb to your computer and use it in GitHub Desktop.
Save cowchimp/0158efe57df3b845927e450fc2b87eeb to your computer and use it in GitHub Desktop.
example of a Jest integration test
{
"presets": ["es2015"]
}
import axios from 'axios';
const baseUrl = 'http://example.com';
export function get(endpoint) {
return axios.get(baseUrl + endpoint);
}
import { get } from './api-wrapper';
export async function fetchEmployees() {
return await get('/employees');
}
{
"name": "demo-jest-integration",
"version": "0.0.1",
"scripts": {
"test": "jest"
},
"dependencies": {
"axios": "0.17.1",
"lodash.maxby": "4.6.0"
},
"devDependencies": {
"babel-core": "6.26.0",
"babel-jest": "21.2.0",
"babel-preset-es2015": "6.24.1",
"jest": "21.2.1"
}
}
import maxBy from 'lodash.maxby';
import { fetchEmployees } from './employees-fetcher';
export async function calculateTopEmployee() {
const allEmployees = await fetchEmployees();
return maxBy(allEmployees, e => e.numOfSales)
}
import { calculateTopEmployee } from './top-employee-provider';
import { get } from './api-wrapper';
jest.mock('./api-wrapper');
test('returns the top-performing employee', async () => {
mockApiResponse('/employees', [
{name: 'foo', numOfSales: 1 },
{name: 'bar', numOfSales: 2 }
]);
const topEmployee = await calculateTopEmployee();
expect(topEmployee).toEqual({ name: 'bar', numOfSales: 2 });
});
function mockApiResponse(endpoint, payload) {
const successfulPromise = new Promise(resolve => process.nextTick(() => resolve(payload)));
get.mockImplementationOnce(e => e === endpoint ? successfulPromise : Promise.reject());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment