retryableImport.spec.jsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import retryableImport from 'app/utils/retryableImport';
  2. describe('retryableImport', function() {
  3. it('can dynamically import successfully on first try', async function() {
  4. const importMock = jest.fn();
  5. importMock.mockReturnValue(
  6. new Promise(resolve =>
  7. resolve({
  8. default: {
  9. foo: 'bar',
  10. },
  11. })
  12. )
  13. );
  14. const result = await retryableImport(() => importMock());
  15. expect(result).toEqual({
  16. foo: 'bar',
  17. });
  18. expect(importMock).toHaveBeenCalledTimes(1);
  19. });
  20. it('does not retry if error was not a webpack chunk loading error', async function() {
  21. const importMock = jest.fn();
  22. importMock.mockReturnValueOnce(
  23. new Promise((resolve, reject) => reject(new Error('Another error happened')))
  24. );
  25. try {
  26. await retryableImport(() => importMock());
  27. } catch (err) {
  28. // do nothing
  29. }
  30. expect(importMock).toHaveBeenCalledTimes(1);
  31. });
  32. it('can fail 2 dynamic imports and succeed on 3rd try', async function() {
  33. const importMock = jest.fn();
  34. importMock
  35. .mockReturnValueOnce(
  36. new Promise((resolve, reject) => reject(new Error('Loading chunk 123 failed')))
  37. )
  38. .mockReturnValueOnce(
  39. new Promise((resolve, reject) => reject(new Error('Loading chunk 123 failed')))
  40. )
  41. .mockReturnValue(
  42. new Promise(resolve =>
  43. resolve({
  44. default: {
  45. foo: 'bar',
  46. },
  47. })
  48. )
  49. );
  50. const result = await retryableImport(() => importMock());
  51. expect(result).toEqual({
  52. foo: 'bar',
  53. });
  54. expect(importMock).toHaveBeenCalledTimes(3);
  55. });
  56. it('only retries 3 times', async function() {
  57. const importMock = jest.fn(
  58. () =>
  59. new Promise((resolve, reject) => reject(new Error('Loading chunk 123 failed')))
  60. );
  61. await expect(retryableImport(() => importMock())).rejects.toThrow(
  62. 'Loading chunk 123 failed'
  63. );
  64. expect(importMock).toHaveBeenCalledTimes(3);
  65. });
  66. });