fetch-json.test.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { expect } from 'chai'
  2. import fetchMock from 'fetch-mock'
  3. import OError from '@overleaf/o-error'
  4. import {
  5. deleteJSON,
  6. getJSON,
  7. postJSON,
  8. putJSON
  9. } from '../../../frontend/js/infrastructure/fetch-json'
  10. describe('fetchJSON', function() {
  11. before(function() {
  12. fetchMock.restore()
  13. })
  14. afterEach(function() {
  15. fetchMock.restore()
  16. })
  17. const headers = {
  18. Accept: 'application/json',
  19. 'Content-Type': 'application/json'
  20. }
  21. it('handles GET requests', function() {
  22. fetchMock.once(
  23. { method: 'GET', url: '/test', headers },
  24. { status: 200, body: { result: 'success' } }
  25. )
  26. return expect(getJSON('/test')).to.eventually.deep.equal({
  27. result: 'success'
  28. })
  29. })
  30. it('handles 4xx responses', function() {
  31. fetchMock.get('/test', {
  32. status: 400,
  33. body: { message: 'The request was invalid' }
  34. })
  35. return expect(getJSON('/test'))
  36. .to.eventually.be.rejectedWith('Bad Request')
  37. .and.be.an.instanceOf(OError)
  38. .to.nested.include({
  39. 'info.response.status': 400,
  40. 'info.data.message': 'The request was invalid'
  41. })
  42. })
  43. it('handles 5xx responses', async function() {
  44. fetchMock.get('/test', { status: 500 })
  45. return expect(getJSON('/test'))
  46. .to.eventually.be.rejectedWith('Internal Server Error')
  47. .and.be.an.instanceOf(OError)
  48. .to.nested.include({
  49. 'info.response.status': 500
  50. })
  51. })
  52. it('handles POST requests', function() {
  53. const body = { example: true }
  54. fetchMock.once(
  55. { method: 'POST', url: '/test', headers, body },
  56. { status: 200, body: { result: 'success' } }
  57. )
  58. return expect(postJSON('/test', { body })).to.eventually.deep.equal({
  59. result: 'success'
  60. })
  61. })
  62. it('handles PUT requests', function() {
  63. const body = { example: true }
  64. fetchMock.once(
  65. { method: 'PUT', url: '/test', headers, body },
  66. { status: 200, body: { result: 'success' } }
  67. )
  68. return expect(putJSON('/test', { body })).to.eventually.deep.equal({
  69. result: 'success'
  70. })
  71. })
  72. it('handles DELETE requests', function() {
  73. fetchMock.once({ method: 'DELETE', url: '/test', headers }, { status: 204 })
  74. return expect(deleteJSON('/test')).to.eventually.deep.equal({})
  75. })
  76. })