Guest User

Untitled

a guest
Dec 15th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. import axios from "axios";
  2. const BASE_URL = "https://jsonplaceholder.typicode.com/";
  3. const URI_USERS = 'users/';
  4.  
  5. /**
  6. * These are the implementation of our functions, which take functions as arguments.
  7. */
  8.  
  9. export const _fetchUsers = async function (_makeApiCall, _URI_USERS) {
  10. return _makeApiCall(_URI_USERS);
  11. }
  12.  
  13.  
  14. export const _fetchUser = async function (_makeApiCall, _URI_USERS, id) {
  15. return _makeApiCall(_URI_USERS + id);
  16. }
  17.  
  18.  
  19. export const _fetchUserStrings = async function (_fetchUser, _parseUser, ...ids) {
  20. const users = await Promise.all(ids.map(id => _fetchUser(id)));
  21. return users.map(user => _parseUser(user));
  22. }
  23. export const _makeApiCall = async function (uri) {
  24. try {
  25. const response = await axios(BASE_URL + uri);
  26. return response.data;
  27. } catch (err) {
  28. throw new Error(err.message);
  29. }
  30. }
  31.  
  32. export function _parseUser(user) {
  33. return `${user.name}:${user.username}`;
  34. }
  35.  
  36.  
  37.  
  38. /**
  39. * Real exports
  40. */
  41. export const makeApiCall = _makeApiCall;
  42. export const parseUser = _parseUser;
  43.  
  44. export const fetchUsers = _fetchUsers.bind(null, _makeApiCall, URI_USERS);
  45. export const fetchUser = _fetchUser.bind(null, _makeApiCall, URI_USERS);
  46. export const fetchUserStrings = _fetchUserStrings.bind(null, _fetchUser, _parseUser);
  47.  
  48. /**
  49. * Our most complicated test
  50. *
  51. */
  52.  
  53. describe("_fetchUserStrings", () => {
  54.  
  55. describe("happy flow", () => {
  56.  
  57. const fetchUserMock = jest.fn((i) => Promise.resolve({
  58. username: "foo",
  59. name: "bar"
  60. }));
  61. const parseUserMock = jest.fn(user => "string");
  62. const fetchUserStrings = _fetchUserStrings.bind(null, fetchUserMock, parseUserMock);
  63.  
  64. it("returns an array of three strings", async () => {
  65.  
  66. expect.assertions(3);
  67. const result = await fetchUserStrings(1, 2, 3);
  68.  
  69. // I'm being a bit lazy here, you could be checking that
  70. // The strings are actually there etc, but whatevs.
  71.  
  72. expect(fetchUserMock).toHaveBeenCalledTimes(3);
  73. expect(parseUserMock).toHaveBeenCalledTimes(3);
  74. expect(result).toHaveLength(3);
  75. })
  76.  
  77. });
  78. });
Add Comment
Please, Sign In to add comment