fetch-json.test.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import { expect } from 'chai'
  2. import fetchMock from 'fetch-mock'
  3. import {
  4. deleteJSON,
  5. FetchError,
  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(FetchError)
  38. .to.nested.include({
  39. message: 'Bad Request',
  40. 'data.message': 'The request was invalid',
  41. 'response.status': 400,
  42. 'info.statusCode': 400,
  43. })
  44. })
  45. it('handles 5xx responses', async function () {
  46. fetchMock.get('/test', { status: 500 })
  47. return expect(getJSON('/test'))
  48. .to.eventually.be.rejectedWith('Internal Server Error')
  49. .and.be.an.instanceOf(FetchError)
  50. .to.nested.include({
  51. 'response.status': 500,
  52. 'info.statusCode': 500,
  53. })
  54. })
  55. it('handles POST requests', function () {
  56. const body = { example: true }
  57. fetchMock.once(
  58. { method: 'POST', url: '/test', headers, body },
  59. { status: 200, body: { result: 'success' } }
  60. )
  61. return expect(postJSON('/test', { body })).to.eventually.deep.equal({
  62. result: 'success',
  63. })
  64. })
  65. it('handles PUT requests', function () {
  66. const body = { example: true }
  67. fetchMock.once(
  68. { method: 'PUT', url: '/test', headers, body },
  69. { status: 200, body: { result: 'success' } }
  70. )
  71. return expect(putJSON('/test', { body })).to.eventually.deep.equal({
  72. result: 'success',
  73. })
  74. })
  75. it('handles DELETE requests', function () {
  76. fetchMock.once({ method: 'DELETE', url: '/test', headers }, { status: 204 })
  77. return expect(deleteJSON('/test')).to.eventually.deep.equal({})
  78. })
  79. })