Skip to content

Instantly share code, notes, and snippets.

@BrianJenney
Created April 9, 2022 20:09
Show Gist options
  • Save BrianJenney/387562236f68ed1647f00aba045b697f to your computer and use it in GitHub Desktop.
Save BrianJenney/387562236f68ed1647f00aba045b697f to your computer and use it in GitHub Desktop.
const { flattenArr, dataFetcher, createList } = require('./myFunc');
const axios = require('axios');
jest.mock('axios', () => ({
get: jest.fn(),
}));
describe.skip('flattenArr', () => {
it('return a non-nested arr', () => {
const input = [1, 2, 3, 4];
const expectedOutput = [1, 2, 3, 4];
expect(flattenArr(input)).toEqual(expectedOutput);
});
it('flattens a nested arr', () => {
const input = [1, 2, 3, [4, 5, [6, 7, [8, [9, [10]]]]]];
const expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
expect(flattenArr(input)).toEqual(expectedOutput);
});
});
describe.skip('dataFetcher', () => {
it('handles a successful response', async () => {
axios.get.mockImplementation(() =>
Promise.resolve({ data: { users: [] } })
);
const data = await dataFetcher();
expect(data).toEqual({ data: { users: [] } });
});
it('handles an error response', async () => {
axios.get.mockImplementation(() => Promise.reject('Boom'));
try {
await dataFetcher();
} catch (e) {
expect(e).toEqual(
new Error({ error: 'Boom', message: 'An Error Occurred' })
);
}
});
});
describe.skip('createList', () => {
it('calls a sorter function if it is available', () => {
const sortFn = jest.fn();
createList([3, 2, 1], sortFn);
expect(sortFn).toBeCalled();
expect(sortFn.mock.calls).toEqual([[[3, 2, 1]]]);
});
it('does not call a sorter function if the array has a length <= 1', () => {
const sortFn = jest.fn();
createList([1], sortFn);
expect(sortFn).not.toBeCalled();
});
it('calls the sorter fn', () => {
const tests = [
//arr sortFn expected
[[2, 3, 1], jest.fn(), true],
[[], jest.fn(), false],
[[1], jest.fn(), false],
];
tests.forEach((test) => {
const [arr, sortFn, expected] = test;
createList(arr, sortFn);
if (expected) {
expect(sortFn).toBeCalled();
}
if (!expected) {
expect(sortFn).not.toBeCalled();
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment